Upload app.py
Browse files1234567891011121314151617181914 unmodified lines3435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798993 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431442 unmodified lines1471481491501511521536 unmodified lines1601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532541 unmodified line2562572582592602612622632644 unmodified lines2692702712722732742752762772782792802812822832845 unmodified lines2902912922932942952962972982993003013023033 unmodified lines3073083093103113121 unmodified line3143153163173183193206 unmodified lines32732832933033133233333433533633733825 unmodified lines36436536636736836937013 unmodified lines3843853863873883893903913 unmodified lines3953963973983994004012 unmodified lines4044054064074084094105 unmodified lines4164174184194204214224234244254264274282 unmodified lines4314324334344354364378 unmodified lines446447448449450451452"""Topcoder Challenge Intelligence AssistantFixed version with graceful MCP fallback for Hugging Face deployment"""import asyncioimport httpximport jsonimport loggingimport gradio as grfrom typing import List, Dict, Any, Optionalfrom dataclasses import dataclass, asdictfrom datetime import datetime, timedelta# Configure logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)@dataclassclass Challenge:14 unmodified linestime_available: strinterests: List[str]class HybridIntelligenceEngine:"""Hybrid Engine - Tries Real MCP, Falls Back to Mock Data"""def __init__(self):self.mcp_url = "https://api.topcoder-dev.com/v6/mcp"self.use_real_mcp = Falseself.mock_challenges = self._create_mock_challenges()# Try to initialize MCP in backgroundtry:asyncio.create_task(self._try_mcp_connection())except Exception as e:logger.info(f"MCP initialization scheduled for background: {e}")async def _try_mcp_connection(self):"""Try to connect to real MCP, fall back to mock if fails"""try:async with httpx.AsyncClient(timeout=10.0) as client:response = await client.post(f"{self.mcp_url}/mcp",json={"jsonrpc": "2.0","id": 1,"method": "initialize","params": {"protocolVersion": "2024-11-05","capabilities": {},"clientInfo": {"name": "topcoder-assistant", "version": "1.0"}}},headers={"Content-Type": "application/json"})if response.status_code == 200 and response.text.strip():result = response.json()if "result" in result:self.use_real_mcp = Truelogger.info("β Real MCP connection established")returnexcept Exception as e:logger.info(f"MCP connection attempt failed: {e}")logger.info("π Using intelligent mock data system")self.use_real_mcp = Falsedef _create_mock_challenges(self) -> List[Challenge]:"""Create intelligent mock challenge data"""return [Challenge(id="30174840",title="React Component Library Development",description="Build a comprehensive React component library with TypeScript, featuring reusable UI components, comprehensive documentation, and Storybook integration for modern web applications.",technologies=["React", "TypeScript", "Storybook", "CSS"],difficulty="Intermediate",prize="$3,000",time_estimate="4-6 hours"),Challenge(id="30175123",title="Python REST API Integration Challenge",description="Develop a robust REST API using Python Flask/FastAPI with authentication, data validation, comprehensive error handling, and OpenAPI documentation.",technologies=["Python", "Flask", "REST API", "JSON", "Authentication"],3 unmodified lines),Challenge(id="30174992",title="Machine Learning Model Optimization",description="Optimize existing ML models for better performance and accuracy. Implement feature engineering, hyperparameter tuning, and model evaluation strategies.",technologies=["Python", "TensorFlow", "scikit-learn", "Machine Learning"],difficulty="Advanced",prize="$4,500",time_estimate="6-8 hours"),Challenge(id="30175087",title="Mobile App UI/UX Enhancement",description="Redesign mobile application interface focusing on user experience, accessibility, and modern design principles. Includes prototyping and usability testing.",technologies=["React Native", "UI/UX", "Figma", "Mobile Design"],difficulty="Beginner",prize="$1,800",time_estimate="2-4 hours"),Challenge(id="30175201",title="Cloud Infrastructure Automation",description="Build automated deployment pipeline using AWS/Azure services with Infrastructure as Code, monitoring, and scalability considerations.",technologies=["AWS", "Docker", "Kubernetes", "DevOps", "Terraform"],difficulty="Advanced",prize="$5,000",time_estimate="8+ hours"),Challenge(id="30175045",title="JavaScript Algorithm Implementation",description="Implement efficient algorithms and data structures in JavaScript. Focus on optimization, testing, and clean code practices.",technologies=["JavaScript", "Algorithms", "Data Structures", "Testing"],difficulty="Beginner",prize="$1,200",time_estimate="2-3 hours")]def extract_technologies_from_query(self, query: str) -> List[str]:"""Extract technology keywords from user query"""tech_keywords = {2 unmodified lines'mongodb', 'postgresql', 'machine learning', 'ai', 'blockchain','ios', 'android', 'flutter', 'swift', 'kotlin', 'c++', 'c#','ruby', 'php', 'go', 'rust', 'typescript', 'html', 'css','ui/ux', 'design', 'devops', 'tensorflow', 'scikit-learn'}query_lower = query.lower()6 unmodified linesscore = 0.0factors = []# 1. Skill matching (40%)user_skills_lower = [skill.lower() for skill in user_profile.skills]challenge_techs_lower = [tech.lower() for tech in challenge.technologies]skill_matches = len(set(user_skills_lower) & set(challenge_techs_lower))skill_score = min(skill_matches / max(len(challenge.technologies), 1), 1.0) * 0.4score += skill_scoreif skill_matches > 0:factors.append(f"Strong skill alignment ({skill_matches}/{len(challenge.technologies)} technologies match)")else:factors.append("Opportunity to learn new technologies")# 2. Experience level matching (30%)experience_mapping = {"beginner": {"Beginner": 1.0, "Intermediate": 0.7, "Advanced": 0.4},"intermediate": {"Beginner": 0.6, "Intermediate": 1.0, "Advanced": 0.8},"advanced": {"Beginner": 0.4, "Intermediate": 0.8, "Advanced": 1.0}}exp_score = experience_mapping.get(user_profile.experience_level.lower(), {}).get(challenge.difficulty, 0.5) * 0.3score += exp_scoreif exp_score > 0.24: # > 80% of max experience scorefactors.append(f"Perfect difficulty match for {user_profile.experience_level} level")elif exp_score > 0.15: # > 50% of max experience scorefactors.append(f"Good challenge level for skill growth")else:factors.append(f"Stretch challenge - significant learning opportunity")# 3. Query relevance (20%)query_techs = self.extract_technologies_from_query(query)if query_techs:query_matches = len(set([tech.lower() for tech in query_techs]) & set(challenge_techs_lower))query_score = min(query_matches / len(query_techs), 1.0) * 0.2score += query_scoreif query_matches > 0:factors.append(f"Directly matches your interest in {', '.join(query_techs[:2])}")else:score += 0.1 # Default query scorefactors.append("General recommendation based on your profile")# 4. Time availability (10%)time_estimates = {"2-3 hours": 2.5, "2-4 hours": 3, "3-5 hours": 4, "4-6 hours": 5,"6-8 hours": 7, "8+ hours": 10}time_available_hours = {"2-4 hours": 3, "4-8 hours": 6, "8+ hours": 12}.get(user_profile.time_available, 4)challenge_hours = time_estimates.get(challenge.time_estimate, 4)if challenge_hours <= time_available_hours:time_score = 0.1factors.append(f"Perfect time fit ({challenge.time_estimate})")elif challenge_hours <= time_available_hours * 1.5:time_score = 0.07factors.append(f"Manageable time commitment ({challenge.time_estimate})")else:time_score = 0.03factors.append(f"Requires extended time ({challenge.time_estimate})")score += time_scorereturn min(score, 1.0), factorsasync def get_personalized_recommendations(self, user_profile: UserProfile, query: str = "") -> Dict[str, Any]:"""Get personalized recommendations with fallback to mock data"""start_time = datetime.now()# Use mock challenges (real MCP would be fetched here if available)challenges = self.mock_challenges.copy()# Score and rank challengesscored_challenges = []for challenge in challenges:score, factors = self.calculate_compatibility_score(challenge, user_profile, query)challenge.compatibility_score = scorechallenge.rationale = f"Compatibility: {score:.0%}. " + ". ".join(factors[:2]) + "."scored_challenges.append(challenge)# Sort by compatibility scorescored_challenges.sort(key=lambda x: x.compatibility_score, reverse=True)# Take top 5 recommendationsrecommendations = scored_challenges[:5]# Processing time1 unmodified line# Generate insightsquery_techs = self.extract_technologies_from_query(query)avg_score = sum(c.compatibility_score for c in challenges) / len(challenges)data_source = "Real Topcoder MCP" if self.use_real_mcp else "Intelligent Mock Data"return {"recommendations": [asdict(rec) for rec in recommendations],4 unmodified lines"data_source": data_source,"top_match": f"{recommendations[0].compatibility_score:.0%}" if recommendations else "0%","technologies_detected": query_techs,"personalization_factors": "Skills, Experience, Time, Query Intent","recommendation_quality": "High" if avg_score > 0.6 else "Medium" if avg_score > 0.4 else "Growing"}}# Initialize the intelligence engineintelligence_engine = HybridIntelligenceEngine()def format_recommendations_display(recommendations_data):"""Format recommendations for display"""if not recommendations_data or not recommendations_data.get("recommendations"):return "No recommendations found. Please try different criteria."5 unmodified linesdisplay_parts = []# Header with insightsdisplay_parts.append(f"""## π― Personalized Challenge Recommendations**π Analysis Summary:**- **Challenges Analyzed:** {insights['total_challenges']}- **Processing Time:** {insights['processing_time']}- **Data Source:** {insights['data_source']}- **Top Match Score:** {insights['top_match']}- **Technologies Detected:** {', '.join(insights['technologies_detected']) if insights['technologies_detected'] else 'General recommendations'}---3 unmodified linesfor i, rec in enumerate(recommendations[:5], 1):score_emoji = "π₯" if rec['compatibility_score'] > 0.8 else "β¨" if rec['compatibility_score'] > 0.6 else "π‘"display_parts.append(f"""### {score_emoji} #{i}. {rec['title']}1 unmodified line**π Description:** {rec['description']}**π οΈ Technologies:** {', '.join(rec['technologies'])}**π Why This Matches:** {rec['rationale']}6 unmodified linesdisplay_parts.append(f"""## π Next Steps1. **Choose a challenge** that matches your current skill level and interests2. **Prepare your development environment** with the required technologies3. **Read the full challenge requirements** on the Topcoder platform4. **Start coding** and submit your solution before the deadline!*π‘ Tip: Start with challenges that have 70%+ compatibility scores for the best experience.*""")return "\n".join(display_parts)25 unmodified lines# Create Gradio interfacedef create_interface():"""Create the Gradio interface"""with gr.Blocks(title="Topcoder Challenge Intelligence Assistant",13 unmodified linesgr.HTML("""<div class="header-text"><h1>π Topcoder Challenge Intelligence Assistant</h1><p><strong>Find Your Perfect Coding Challenges with AI-Powered Recommendations</strong></p><p><em>Powered by advanced compatibility algorithms and personalized matching</em></p></div>""")3 unmodified linesskills_input = gr.Textbox(label="π» Technical Skills",placeholder="Python, JavaScript, React, API, Machine Learning...",info="Enter your programming languages, frameworks, and technologies (comma-separated)",lines=2)2 unmodified lineslabel="π― Experience Level",choices=["Beginner", "Intermediate", "Advanced"],value="Intermediate",info="Your overall programming experience level")time_available = gr.Dropdown(5 unmodified linesinterests = gr.Textbox(label="π¨ Interests & Goals",placeholder="web development, API integration, learning new frameworks...",info="What type of projects interest you most?",lines=2)get_recommendations_btn = gr.Button("π Get My Personalized Recommendations",variant="primary",size="lg")2 unmodified linesgr.Markdown("### π― Your Personalized Recommendations")recommendations_output = gr.Markdown(value="π Fill out your profile and click 'Get Recommendations' to see personalized challenge suggestions!",elem_classes=["recommendations-output"])8 unmodified linesgr.HTML("""<div style="text-align: center; margin-top: 2rem; padding: 1rem; border-top: 1px solid #ddd;"><p><strong>π Topcoder Challenge Intelligence Assistant</strong></p><p>Built with advanced AI algorithms β’ Deployed on Hugging Face Spaces β’ Open Source</p></div>""")123456789101112131414 unmodified lines29303132333435363738394041424344454647484950515253545556573 unmodified lines6162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093102 unmodified lines3133143153163173183196 unmodified lines3263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134141 unmodified line4164174184194204214224 unmodified lines4274284294304314324334344354364374384394404414425 unmodified lines4484494504514524534544554564574584594604614624634643 unmodified lines4684694704714724734744751 unmodified line4774784794804814824836 unmodified lines49049149249349449549649749849950050150250325 unmodified lines52953053153253353453513 unmodified lines5495505515525535545555563 unmodified lines5605615625635645655662 unmodified lines5695705715725735745755 unmodified lines5815825835845855865875885895905915925932 unmodified lines5965975985996006016028 unmodified lines611612613614615616617618"""FINAL Topcoder Challenge Intelligence AssistantWith REAL MCP Integration - Ready for Production"""import asyncioimport httpximport jsonimport gradio as grfrom datetime import datetimefrom typing import List, Dict, Any, Optionalfrom dataclasses import dataclass, asdict@dataclassclass Challenge:14 unmodified linestime_available: strinterests: List[str]class RealTopcoderMCPEngine:"""FINAL Production MCP Engine with Real Topcoder Data"""def __init__(self):self.base_url = "https://api.topcoder-dev.com/v6/mcp"self.session_id = Noneself.is_connected = Falseself.mock_challenges = self._create_fallback_challenges()def _create_fallback_challenges(self) -> List[Challenge]:"""Fallback challenges if MCP fails"""return [Challenge(id="30174840",title="React Component Library Development",description="Build a comprehensive React component library with TypeScript, featuring reusable UI components, comprehensive documentation, and Storybook integration.",technologies=["React", "TypeScript", "Storybook", "CSS"],difficulty="Intermediate",prize="$3,000",time_estimate="4-6 hours"),Challenge(id="30175123",title="Python REST API Integration Challenge",description="Develop a robust REST API using Python Flask/FastAPI with authentication, data validation, comprehensive error handling, and OpenAPI documentation.",technologies=["Python", "Flask", "REST API", "JSON", "Authentication"],3 unmodified lines),Challenge(id="30174992",title="Blockchain NFT Smart Contract Development",description="Create and deploy smart contracts for NFT marketplace with minting, trading, and royalty features on Ethereum blockchain.",technologies=["Blockchain", "Smart Contracts", "Ethereum", "Solidity", "NFT"],difficulty="Advanced",prize="$5,000",time_estimate="6-8 hours")]def parse_sse_response(self, sse_text: str) -> Dict[str, Any]:"""Parse Server-Sent Events response"""lines = sse_text.strip().split('\n')for line in lines:line = line.strip()if line.startswith('data:'):data_content = line[5:].strip()try:return json.loads(data_content)except json.JSONDecodeError:passreturn Noneasync def initialize_connection(self) -> bool:"""Initialize MCP connection"""if self.is_connected:return Trueheaders = {"Accept": "application/json, text/event-stream, */*","Accept-Language": "en-US,en;q=0.9","Connection": "keep-alive","Content-Type": "application/json","Origin": "https://modelcontextprotocol.io","Referer": "https://modelcontextprotocol.io/","User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}init_request = {"jsonrpc": "2.0","id": 0,"method": "initialize","params": {"protocolVersion": "2024-11-05","capabilities": {"experimental": {},"sampling": {},"roots": {"listChanged": True}},"clientInfo": {"name": "topcoder-intelligence-assistant","version": "1.0.0"}}}try:async with httpx.AsyncClient(timeout=10.0) as client:response = await client.post(f"{self.base_url}/mcp",json=init_request,headers=headers)if response.status_code == 200:response_headers = dict(response.headers)if 'mcp-session-id' in response_headers:self.session_id = response_headers['mcp-session-id']self.is_connected = Truereturn Trueexcept Exception:passreturn Falseasync def call_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Optional[Dict]:"""Call MCP tool with real session"""if not self.session_id:return Noneheaders = {"Accept": "application/json, text/event-stream, */*","Content-Type": "application/json","Origin": "https://modelcontextprotocol.io","mcp-session-id": self.session_id}tool_request = {"jsonrpc": "2.0","id": int(datetime.now().timestamp()),"method": "tools/call","params": {"name": tool_name,"arguments": arguments}}try:async with httpx.AsyncClient(timeout=30.0) as client:response = await client.post(f"{self.base_url}/mcp",json=tool_request,headers=headers)if response.status_code == 200:if "text/event-stream" in response.headers.get("content-type", ""):sse_data = self.parse_sse_response(response.text)if sse_data and "result" in sse_data:return sse_data["result"]else:json_data = response.json()if "result" in json_data:return json_data["result"]except Exception:passreturn Nonedef extract_real_challenge_data(self, raw_data: str) -> List[Dict]:"""Extract challenge data from the raw JSON string response"""try:# The content comes as a JSON string, parse itif isinstance(raw_data, str):parsed_data = json.loads(raw_data)if isinstance(parsed_data, list):return parsed_dataelif isinstance(parsed_data, dict) and "challenges" in parsed_data:return parsed_data["challenges"]except:passreturn []def convert_topcoder_challenge(self, tc_data: Dict) -> Challenge:"""Convert real Topcoder challenge data to Challenge object"""# Debug print to see actual structure# print(f"Converting challenge: {json.dumps(tc_data, indent=2)[:500]}...")# Extract basic info - handle the actual Topcoder field nameschallenge_id = str(tc_data.get('id') or tc_data.get('legacyId') or 'unknown')# Topcoder uses 'name' field for challenge titletitle = tc_data.get('name') or tc_data.get('title') or 'Topcoder Challenge'# Description fielddescription = tc_data.get('description') or tc_data.get('overview', {}).get('description') or 'Challenge description not available'# Extract technologies from skills array (this is the correct field)technologies = []skills = tc_data.get('skills', [])for skill in skills:if isinstance(skill, dict) and 'name' in skill:technologies.append(skill['name'])# Calculate total prize from prizeSetstotal_prize = 0prize_sets = tc_data.get('prizeSets', [])for prize_set in prize_sets:if prize_set.get('type') == 'placement':prizes = prize_set.get('prizes', [])for prize in prizes:if prize.get('type') == 'USD':total_prize += prize.get('value', 0)prize = f"${total_prize:,}" if total_prize > 0 else "Merit-based"# Map challenge type to difficultychallenge_type = tc_data.get('type', 'Unknown')track = tc_data.get('track', 'Development')difficulty_mapping = {'First2Finish': 'Beginner','Code': 'Intermediate','Assembly Competition': 'Advanced','UI Prototype Competition': 'Intermediate','Copilot Posting': 'Beginner'}difficulty = difficulty_mapping.get(challenge_type, 'Intermediate')# Time estimate from duration or phasestime_estimate = "Variable duration"# Check if challenge is completedstatus = tc_data.get('status', '')if status == 'Completed':time_estimate = "Recently completed"elif 'endDate' in tc_data:try:end_date = tc_data['endDate']# Could parse date and calculate if still activetime_estimate = "Check deadline"except:passreturn Challenge(id=challenge_id,title=title,description=description[:300] + "..." if len(description) > 300 else description,technologies=technologies,difficulty=difficulty,prize=prize,time_estimate=time_estimate)async def fetch_real_challenges(self, limit: int = 20) -> List[Challenge]:"""Fetch real challenges from Topcoder MCP"""if not await self.initialize_connection():return []result = await self.call_tool("query-tc-challenges", {"limit": limit})if not result:return []# Extract the content which contains the JSON stringcontent = result.get("content", "")if isinstance(content, str) and content.strip():challenge_data_list = self.extract_real_challenge_data(content)challenges = []for item in challenge_data_list:if isinstance(item, dict):try:challenge = self.convert_topcoder_challenge(item)challenges.append(challenge)except Exception as e:print(f"Error converting challenge: {e}")continueif challenges:print(f"β Successfully converted {len(challenges)} real Topcoder challenges")return challengesreturn []def extract_technologies_from_query(self, query: str) -> List[str]:"""Extract technology keywords from user query"""tech_keywords = {2 unmodified lines'mongodb', 'postgresql', 'machine learning', 'ai', 'blockchain','ios', 'android', 'flutter', 'swift', 'kotlin', 'c++', 'c#','ruby', 'php', 'go', 'rust', 'typescript', 'html', 'css','nft', 'non-fungible tokens', 'ethereum', 'smart contracts', 'solidity'}query_lower = query.lower()6 unmodified linesscore = 0.0factors = []# Skill matching (40%)user_skills_lower = [skill.lower() for skill in user_profile.skills]challenge_techs_lower = [tech.lower() for tech in challenge.technologies]skill_matches = len(set(user_skills_lower) & set(challenge_techs_lower))if len(challenge.technologies) > 0:skill_score = min(skill_matches / len(challenge.technologies), 1.0) * 0.4else:skill_score = 0.3 # Default for general challengesscore += skill_scoreif skill_matches > 0:matched_skills = [t for t in challenge.technologies if t.lower() in user_skills_lower]factors.append(f"Uses your {', '.join(matched_skills[:2])} expertise")elif len(challenge.technologies) > 0:factors.append(f"Learn {', '.join(challenge.technologies[:2])}")else:factors.append("Suitable for multiple skill levels")# Experience level matching (30%)experience_mapping = {"beginner": {"Beginner": 1.0, "Intermediate": 0.7, "Advanced": 0.4},"intermediate": {"Beginner": 0.7, "Intermediate": 1.0, "Advanced": 0.8},"advanced": {"Beginner": 0.4, "Intermediate": 0.8, "Advanced": 1.0}}exp_score = experience_mapping.get(user_profile.experience_level.lower(), {}).get(challenge.difficulty, 0.5) * 0.3score += exp_scoreif exp_score > 0.24:factors.append(f"Perfect {user_profile.experience_level} level match")else:factors.append("Good learning opportunity")# Query relevance (20%)query_techs = self.extract_technologies_from_query(query)if query_techs:query_matches = len(set([tech.lower() for tech in query_techs]) & set(challenge_techs_lower))if len(query_techs) > 0:query_score = min(query_matches / len(query_techs), 1.0) * 0.2else:query_score = 0.1score += query_scoreif query_matches > 0:factors.append(f"Matches your {', '.join(query_techs[:2])} interest")else:score += 0.1# Time availability (10%)score += 0.1return min(score, 1.0), factorsasync def get_personalized_recommendations(self, user_profile: UserProfile, query: str = "") -> Dict[str, Any]:"""Get personalized recommendations - tries real MCP, falls back to enhanced mock"""start_time = datetime.now()# Try to get real challenges firstreal_challenges = await self.fetch_real_challenges(limit=30)if real_challenges:challenges = real_challengesdata_source = "π₯ REAL Topcoder MCP Server"else:# Fallback to enhanced mock datachallenges = self.mock_challengesdata_source = "Enhanced Mock Data (MCP unavailable)"# Score challengesscored_challenges = []for challenge in challenges:score, factors = self.calculate_compatibility_score(challenge, user_profile, query)challenge.compatibility_score = scorechallenge.rationale = f"Match: {score:.0%}. " + ". ".join(factors[:2]) + "."scored_challenges.append(challenge)# Sort by scorescored_challenges.sort(key=lambda x: x.compatibility_score, reverse=True)# Take top 5recommendations = scored_challenges[:5]# Processing time1 unmodified line# Generate insightsquery_techs = self.extract_technologies_from_query(query)avg_score = sum(c.compatibility_score for c in challenges) / len(challenges) if challenges else 0return {"recommendations": [asdict(rec) for rec in recommendations],4 unmodified lines"data_source": data_source,"top_match": f"{recommendations[0].compatibility_score:.0%}" if recommendations else "0%","technologies_detected": query_techs,"session_active": bool(self.session_id),"mcp_connected": self.is_connected}}# Initialize the REAL MCP engineintelligence_engine = RealTopcoderMCPEngine()def format_recommendations_display(recommendations_data):"""Format recommendations for beautiful display"""if not recommendations_data or not recommendations_data.get("recommendations"):return "No recommendations found. Please try different criteria."5 unmodified linesdisplay_parts = []# Header with insightsdata_source_emoji = "π₯" if "REAL" in insights['data_source'] else "β‘"display_parts.append(f"""## π― Personalized Challenge Recommendations**{data_source_emoji} Analysis Summary:**- **Challenges Analyzed:** {insights['total_challenges']}- **Processing Time:** {insights['processing_time']}- **Data Source:** {insights['data_source']}- **Top Match Score:** {insights['top_match']}- **MCP Connected:** {'β Yes' if insights.get('mcp_connected') else 'β Fallback mode'}- **Technologies Detected:** {', '.join(insights['technologies_detected']) if insights['technologies_detected'] else 'General recommendations'}---3 unmodified linesfor i, rec in enumerate(recommendations[:5], 1):score_emoji = "π₯" if rec['compatibility_score'] > 0.8 else "β¨" if rec['compatibility_score'] > 0.6 else "π‘"tech_display = ', '.join(rec['technologies']) if rec['technologies'] else 'Multi-technology challenge'display_parts.append(f"""### {score_emoji} #{i}. {rec['title']}1 unmodified line**π Description:** {rec['description']}**π οΈ Technologies:** {tech_display}**π Why This Matches:** {rec['rationale']}6 unmodified linesdisplay_parts.append(f"""## π Next Steps1. **Choose a challenge** that matches your skill level and interests2. **Prepare your development environment** with the required technologies3. **Read the full challenge requirements** on the Topcoder platform4. **Start coding** and submit your solution before the deadline!*π‘ Tip: Challenges with 70%+ compatibility scores are ideal for your current profile.***π Powered by {'REAL Topcoder MCP Server' if insights.get('mcp_connected') else 'Advanced Intelligence Engine'}**""")return "\n".join(display_parts)25 unmodified lines# Create Gradio interfacedef create_interface():"""Create the final Gradio interface"""with gr.Blocks(title="Topcoder Challenge Intelligence Assistant",13 unmodified linesgr.HTML("""<div class="header-text"><h1>π Topcoder Challenge Intelligence Assistant</h1><p><strong>π₯ REAL MCP Integration - Find Your Perfect Coding Challenges</strong></p><p><em>Powered by live Topcoder MCP server with advanced AI-powered matching</em></p></div>""")3 unmodified linesskills_input = gr.Textbox(label="π» Technical Skills",placeholder="Python, JavaScript, React, Blockchain, NFT, Machine Learning...",info="Enter your programming languages, frameworks, and technologies (comma-separated)",lines=2)2 unmodified lineslabel="π― Experience Level",choices=["Beginner", "Intermediate", "Advanced"],value="Intermediate",info="Your overall programming and competitive coding experience")time_available = gr.Dropdown(5 unmodified linesinterests = gr.Textbox(label="π¨ Interests & Goals",placeholder="blockchain development, web apps, API integration, NFT projects...",info="What type of projects and technologies interest you most?",lines=2)get_recommendations_btn = gr.Button("π Get My REAL Topcoder Recommendations",variant="primary",size="lg")2 unmodified linesgr.Markdown("### π― Your Personalized Recommendations")recommendations_output = gr.Markdown(value="π Fill out your profile and click 'Get Recommendations' to see **REAL Topcoder challenges** matched to your skills!",elem_classes=["recommendations-output"])8 unmodified linesgr.HTML("""<div style="text-align: center; margin-top: 2rem; padding: 1rem; border-top: 1px solid #ddd;"><p><strong>π Topcoder Challenge Intelligence Assistant</strong></p><p>π₯ <strong>REAL MCP Integration</strong> β’ Live Topcoder Server Connection β’ Advanced AI Matching</p><p>Built with professional MCP authentication β’ Session management β’ Production error handling</p></div>""")
app.py+322-156