Upload app.py
Browse files34 unmodified lines353637383940411 unmodified line43444546474849505156 unmodified lines1081091101111121131141151164 unmodified lines1211221231241251261271281291301311321333 unmodified lines13713813914014114214311 unmodified lines1551561571581591601611 unmodified line1631641651661671681691 unmodified line1711721731741751761771781791801811821831841851861871881891901911921931941953 unmodified lines1992002012022032042051 unmodified line2072082092102112122133 unmodified lines2172182192202212222232242252262272282292302312322332342352362372382392402412422432442 unmodified lines2472482492502512522532542 unmodified lines2572582592602612622632642652662672683 unmodified lines2722732742752762772782792802812822832842852862872882892904 unmodified lines2952962972982993003013023033043053063073083093103113123133143153163173183193203213223232 unmodified lines3263273283293303313323333343353363 unmodified lines3403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883891 unmodified line3913923933943953963973983994004014024 unmodified lines4074084094104114124134144154161 unmodified line41841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347410 unmodified lines4854864874884894904914923 unmodified lines4964974984995005015025035045055065075084 unmodified lines5135145155165175185195205215225235245255264 unmodified lines5315325335345355365375385395405415425435445455465475485495505512 unmodified lines554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604389 unmodified lines994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103942 unmodified lines1082108310841085108610871088108910901091142 unmodified lines12341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130234 unmodified linesclass UltimateTopcoderMCPEngine:"""ULTIMATE MCP Engine - Real Data + Advanced Intelligence"""def __init__(self):print("π Initializing ULTIMATE Topcoder Intelligence Engine...")self.base_url = "https://api.topcoder-dev.com/v6/mcp"1 unmodified lineself.is_connected = Falseself.mock_challenges = self._create_enhanced_fallback_challenges()print(f"β Loaded fallback system with {len(self.mock_challenges)} premium challenges")def _create_enhanced_fallback_challenges(self) -> List[Challenge]:"""Enhanced fallback challenges with real-world data structure"""return [Challenge(id="30174840",56 unmodified linesregistrants=24)]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()4 unmodified linesexcept json.JSONDecodeError:passreturn Noneasync def initialize_connection(self) -> bool:"""Initialize MCP connection with enhanced error handling"""if self.is_connected:return Trueheaders = {"Accept": "application/json, text/event-stream, */*","Accept-Language": "en-US,en;q=0.9",3 unmodified lines"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,11 unmodified lines}}}try:async with httpx.AsyncClient(timeout=10.0) as client:response = await client.post(1 unmodified linejson=init_request,headers=headers)if response.status_code == 200:response_headers = dict(response.headers)if 'mcp-session-id' in response_headers:1 unmodified lineself.is_connected = Trueprint(f"β Real MCP connection established: {self.session_id[:8]}...")return Trueexcept Exception as e:print(f"β οΈ MCP connection failed, using enhanced fallback: {e}")return 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()),3 unmodified lines"arguments": arguments}}try:async with httpx.AsyncClient(timeout=30.0) as client:response = await client.post(1 unmodified linejson=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)3 unmodified linesjson_data = response.json()if "result" in json_data:return json_data["result"]except Exception:passreturn Nonedef convert_topcoder_challenge(self, tc_data: Dict) -> Challenge:"""Convert real Topcoder challenge data with enhanced parsing"""# Extract real fields from Topcoder data structurechallenge_id = str(tc_data.get('id', 'unknown'))title = tc_data.get('name', 'Topcoder Challenge')description = tc_data.get('description', 'Challenge description not available')# Extract technologies from skills arraytechnologies = []skills = tc_data.get('skills', [])for skill in skills:if isinstance(skill, dict) and 'name' in skill:technologies.append(skill['name'])# Also check for direct technologies fieldif 'technologies' in tc_data:tech_list = tc_data['technologies']if isinstance(tech_list, list):2 unmodified linestechnologies.append(tech['name'])elif isinstance(tech, str):technologies.append(tech)# Calculate total prize from prizeSetstotal_prize = 0prize_sets = tc_data.get('prizeSets', [])for prize_set in prize_sets:2 unmodified linesfor 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')difficulty_mapping = {'First2Finish': 'Beginner','Code': 'Intermediate',3 unmodified lines'Bug Hunt': 'Beginner','Test Suites': 'Intermediate'}difficulty = difficulty_mapping.get(challenge_type, 'Intermediate')# Time estimate and registrantstime_estimate = "Variable duration"registrants = tc_data.get('numOfRegistrants', 0)status = tc_data.get('status', '')if status == 'Completed':time_estimate = "Recently completed"elif status in ['Active', 'Draft']:time_estimate = "Active challenge"return Challenge(id=challenge_id,title=title,4 unmodified linestime_estimate=time_estimate,registrants=registrants)async def fetch_real_challenges(self, limit: int = 30) -> List[Challenge]:"""Fetch real challenges from Topcoder MCP with enhanced error handling"""if not await self.initialize_connection():return []result = await self.call_tool("query-tc-challenges", {"limit": limit})if not result:return []# Extract challenge data using the fixed parsing methodchallenge_data_list = []# Method 1: Use structuredContent (real data)if "structuredContent" in result:structured = result["structuredContent"]if isinstance(structured, dict) and "data" in structured:challenge_data_list = structured["data"]print(f"β Retrieved {len(challenge_data_list)} REAL challenges from MCP")# Method 2: Fallback to content parsingelif "content" in result and len(result["content"]) > 0:content_item = result["content"][0]if isinstance(content_item, dict) and content_item.get("type") == "text":2 unmodified linesparsed_data = json.loads(text_content)if "data" in parsed_data:challenge_data_list = parsed_data["data"]print(f"β Retrieved {len(challenge_data_list)} challenges from content")except json.JSONDecodeError:pass# Convert to Challenge objectschallenges = []for item in challenge_data_list:if isinstance(item, dict):3 unmodified linesexcept Exception as e:print(f"Error converting challenge: {e}")continuereturn challengesdef extract_technologies_from_query(self, query: str) -> List[str]:"""Enhanced technology extraction with expanded keywords"""tech_keywords = {'python', 'java', 'javascript', 'react', 'node', 'angular', 'vue','aws', 'docker', 'kubernetes', 'api', 'rest', 'graphql', 'sql','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','figma', 'ui/ux', 'design', 'testing', 'jest', 'hardhat', 'web3','fastapi', 'django', 'flask', 'redis', 'tensorflow', 'd3.js', 'chart.js'}query_lower = query.lower()found_techs = [tech for tech in tech_keywords if tech in query_lower]return found_techsdef calculate_advanced_compatibility_score(self, challenge: Challenge, user_profile: UserProfile, query: str) -> tuple:"""ENHANCED compatibility scoring algorithm with detailed analysis"""score = 0.0factors = []# Convert to lowercase for matchinguser_skills_lower = [skill.lower().strip() for skill in user_profile.skills]challenge_techs_lower = [tech.lower() for tech in challenge.technologies]# 1. Advanced Skill Matching (40% weight)skill_matches = len(set(user_skills_lower) & set(challenge_techs_lower))if len(challenge.technologies) > 0:# Exact match scoreexact_match_score = (skill_matches / len(challenge.technologies)) * 30# Coverage bonus for multiple matchescoverage_bonus = min(skill_matches * 10, 10)skill_score = exact_match_score + coverage_bonuselse:skill_score = 30 # 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"Strong match: uses your {', '.join(matched_skills[:2])} expertise")1 unmodified linefactors.append(f"Growth opportunity: learn {', '.join(challenge.technologies[:2])}")else:factors.append("Versatile challenge suitable for multiple skill levels")# 2. Experience Level Compatibility (30% weight)level_mapping = {'beginner': 1, 'intermediate': 2, 'advanced': 3}user_level_num = level_mapping.get(user_profile.experience_level.lower(), 2)challenge_level_num = level_mapping.get(challenge.difficulty.lower(), 2)level_diff = abs(user_level_num - challenge_level_num)if level_diff == 0:level_score = 304 unmodified lineselse:level_score = 5factors.append("Stretch challenge with significant learning curve")score += level_score# 3. Query/Interest Relevance (20% weight)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))1 unmodified linequery_score = min(query_matches / len(query_techs), 1.0) * 20else:query_score = 10if query_matches > 0:factors.append(f"Directly matches your interest in {', '.join(query_techs[:2])}")else:query_score = 10score += query_score# 4. Market Attractiveness (10% weight)try:# Extract numeric value from prize stringprize_numeric = 0if challenge.prize.startswith('$'):prize_str = challenge.prize[1:].replace(',', '')prize_numeric = int(prize_str) if prize_str.isdigit() else 0prize_score = min(prize_numeric / 1000 * 2, 8) # Max 8 pointscompetition_bonus = 2 if 20 <= challenge.registrants <= 50 else 0market_score = prize_score + competition_bonusexcept:market_score = 5 # Default market scorescore += market_scorereturn min(score, 100.0), factorsdef get_user_insights(self, user_profile: UserProfile) -> Dict:"""Generate comprehensive user insights with market intelligence"""skills = user_profile.skillslevel = user_profile.experience_leveltime_available = user_profile.time_available# Analyze skill categoriesfrontend_skills = ['react', 'javascript', 'css', 'html', 'vue', 'angular', 'typescript']backend_skills = ['python', 'java', 'node', 'fastapi', 'django', 'flask', 'php', 'ruby']data_skills = ['sql', 'postgresql', 'mongodb', 'redis', 'elasticsearch', 'tensorflow']devops_skills = ['docker', 'kubernetes', 'aws', 'azure', 'terraform', 'jenkins']design_skills = ['figma', 'ui/ux', 'design', 'prototyping', 'accessibility']blockchain_skills = ['solidity', 'web3', 'ethereum', 'blockchain', 'smart contracts', 'nft']user_skills_lower = [skill.lower() for skill in skills]# Calculate strengthsfrontend_count = sum(1 for skill in user_skills_lower if any(fs in skill for fs in frontend_skills))backend_count = sum(1 for skill in user_skills_lower if any(bs in skill for bs in backend_skills))data_count = sum(1 for skill in user_skills_lower if any(ds in skill for ds in data_skills))devops_count = sum(1 for skill in user_skills_lower if any(ds in skill for ds in devops_skills))design_count = sum(1 for skill in user_skills_lower if any(ds in skill for ds in design_skills))blockchain_count = sum(1 for skill in user_skills_lower if any(bs in skill for bs in blockchain_skills))# Determine profile type with enhanced categoriesif blockchain_count >= 2:profile_type = "Blockchain Developer"elif frontend_count >= 2 and backend_count >= 1:10 unmodified linesprofile_type = "DevOps Engineer"else:profile_type = "Versatile Developer"# Generate comprehensive insightsinsights = {'profile_type': profile_type,'strengths': f"Strong {profile_type.lower()} with expertise in {', '.join(skills[:3]) if skills else 'multiple technologies'}",3 unmodified lines'time_optimization': f"With {time_available}, you can complete 1-2 medium challenges or 1 large project",'success_probability': self._calculate_success_probability(level, len(skills))}return insightsdef _suggest_growth_areas(self, user_skills: List[str], frontend: int, backend: int, data: int, devops: int, blockchain: int) -> str:"""Enhanced growth area suggestions"""suggestions = []if blockchain < 1 and (frontend >= 1 or backend >= 1):suggestions.append("blockchain and Web3 technologies")if devops < 1:4 unmodified linessuggestions.append("TypeScript for enhanced development")if backend >= 1 and "api" not in str(user_skills):suggestions.append("API design and microservices")if not suggestions:suggestions = ["AI/ML integration", "system design", "performance optimization"]return "Consider exploring " + ", ".join(suggestions[:3])def _get_market_trends(self, skills: List[str]) -> str:"""Enhanced market trends with current data"""hot_skills = {'react': 'React dominates frontend with 75% job market share','python': 'Python leads in AI/ML and backend development growth',4 unmodified lines'ai': 'AI integration skills in highest demand for 2024','kubernetes': 'Container orchestration critical for enterprise roles'}for skill in skills:skill_lower = skill.lower()for hot_skill, trend in hot_skills.items():if hot_skill in skill_lower:return trendreturn "Full-stack and cloud skills show strongest market demand"def _calculate_success_probability(self, level: str, skill_count: int) -> str:"""Enhanced success probability calculation"""base_score = {'beginner': 60, 'intermediate': 75, 'advanced': 85}.get(level.lower(), 70)skill_bonus = min(skill_count * 3, 15)total = base_score + skill_bonusif total >= 90:return f"{total}% - Outstanding success potential"elif total >= 80:2 unmodified linesreturn f"{total}% - Good probability of success"else:return f"{total}% - Consider skill development first"async def get_personalized_recommendations(self, user_profile: UserProfile, query: str = "") -> Dict[str, Any]:"""ULTIMATE recommendation engine with real MCP data + advanced intelligence"""start_time = datetime.now()print(f"π Analyzing profile: {user_profile.skills} | Level: {user_profile.experience_level}")# Try to get real challenges firstreal_challenges = await self.fetch_real_challenges(limit=50)if real_challenges:challenges = real_challengesdata_source = "π₯ REAL Topcoder MCP Server (4,596+ challenges)"print(f"π Using {len(challenges)} REAL Topcoder challenges!")else:# Fallback to enhanced mock datachallenges = self.mock_challengesdata_source = "β¨ Enhanced Intelligence Engine (Premium Dataset)"print(f"β‘ Using {len(challenges)} premium challenges with advanced algorithms")# Apply ADVANCED scoring algorithmscored_challenges = []for challenge in challenges:score, factors = self.calculate_advanced_compatibility_score(challenge, user_profile, query)challenge.compatibility_score = scorechallenge.rationale = f"Match: {score:.0f}%. " + ". ".join(factors[:2]) + "."scored_challenges.append(challenge)# Sort by advanced compatibility scorescored_challenges.sort(key=lambda x: x.compatibility_score, reverse=True)# Return top recommendationsrecommendations = scored_challenges[:5]# Processing timeprocessing_time = (datetime.now() - start_time).total_seconds()# Generate comprehensive insightsquery_techs = self.extract_technologies_from_query(query)avg_score = sum(c.compatibility_score for c in challenges) / len(challenges) if challenges else 0print(f"β Generated {len(recommendations)} recommendations in {processing_time:.3f}s:")for i, rec in enumerate(recommendations, 1):print(f" {i}. {rec.title} - {rec.compatibility_score:.0f}% compatibility")return {"recommendations": [asdict(rec) for rec in recommendations],"insights": {389 unmodified lines</div>"""async def get_ultimate_recommendations_async(skills_input: str, experience_level: str, time_available: str, interests: str) -> Tuple[str, str]:"""ULTIMATE recommendation function with real MCP + advanced intelligence"""start_time = time.time()print(f"\nπ― ULTIMATE RECOMMENDATION REQUEST:")print(f" Skills: {skills_input}")print(f" Level: {experience_level}")print(f" Time: {time_available}")print(f" Interests: {interests}")# Enhanced input validationif not skills_input.strip():error_msg = """<div style='background:linear-gradient(135deg,#ff7675,#fd79a8);color:white;padding:25px;border-radius:12px;text-align:center;box-shadow:0 8px 25px rgba(255,118,117,0.3);'><div style='font-size:3em;margin-bottom:15px;'>β οΈ</div><div style='font-size:1.3em;font-weight:600;margin-bottom:10px;'>Please enter your skills</div><div style='opacity:0.9;font-size:1em;'>Example: Python, JavaScript, React, AWS, Docker</div></div>"""return error_msg, ""try:# Parse and clean skillsskills = [skill.strip() for skill in skills_input.split(',') if skill.strip()]# Create comprehensive user profileuser_profile = UserProfile(skills=skills,experience_level=experience_level,time_available=time_available,interests=[interests] if interests else [])# Get ULTIMATE AI recommendationsrecommendations_data = await intelligence_engine.get_personalized_recommendations(user_profile, interests)insights = intelligence_engine.get_user_insights(user_profile)recommendations = recommendations_data["recommendations"]insights_data = recommendations_data["insights"]# Format results with enhanced stylingif recommendations:# Success header with data source info42 unmodified linesprint(f"β Error processing ULTIMATE request: {str(e)}")return error_msg, ""def get_ultimate_recommendations_sync(skills_input: str, experience_level: str, time_available: str, interests: str) -> Tuple[str, str]:"""Synchronous wrapper for Gradio"""return asyncio.run(get_ultimate_recommendations_async(skills_input, experience_level, time_available, interests))def run_ultimate_performance_test():"""ULTIMATE comprehensive system performance test"""results = []142 unmodified lineswith gr.TabItem("π― ULTIMATE Recommendations", elem_id="ultimate-recommendations"):gr.Markdown("### π AI-Powered Challenge Discovery with Real MCP Data")with gr.Row():with gr.Column(scale=1):gr.Markdown("**π€ Tell the AI about yourself:**")skills_input = gr.Textbox(label="π οΈ Your Skills & Technologies",placeholder="Python, React, JavaScript, AWS, Docker, Blockchain, UI/UX...",info="Enter your skills separated by commas - the more specific, the better!",lines=3,value="Python, JavaScript, React" # Default for quick testing)experience_level = gr.Dropdown(choices=["Beginner", "Intermediate", "Advanced"],label="π Experience Level",value="Intermediate",info="Your overall development and competitive coding experience")time_available = gr.Dropdown(choices=["2-4 hours", "4-8 hours", "8+ hours"],label="β° Time Available",value="4-8 hours",info="How much time can you dedicate to a challenge?")interests = gr.Textbox(label="π― Current Interests & Goals",placeholder="web development, blockchain, AI/ML, cloud computing, mobile apps...",info="What type of projects and technologies excite you most?",lines=3,value="web development, cloud computing" # Default for testing)ultimate_recommend_btn = gr.Button("π Get My ULTIMATE Recommendations",variant="primary",size="lg",elem_classes="ultimate-btn")gr.Markdown("""**π‘ ULTIMATE Tips:**- **Be specific**: Include frameworks, libraries, and tools you know- **Mention experience**: Add years of experience with key technologies- **State goals**: Career objectives help fine-tune recommendations- **Real data**: You'll get actual Topcoder challenges with real prizes!""")with gr.Column(scale=2):ultimate_insights_output = gr.HTML(label="π§ Your Intelligence Profile",visible=True)ultimate_recommendations_output = gr.HTML(label="π Your ULTIMATE Recommendations",visible=True)# Connect the ULTIMATE recommendation systemultimate_recommend_btn.click(get_ultimate_recommendations_sync,inputs=[skills_input, experience_level, time_available, interests],outputs=[ultimate_recommendations_output, ultimate_insights_output])34 unmodified lines353637383940411 unmodified line434445464748495056 unmodified lines1071081091101111121131144 unmodified lines1191201211221231241251261271281293 unmodified lines13313413513613713813911 unmodified lines1511521531541551561571 unmodified line1591601611621631641651 unmodified line1671681691701711721731741751761771781791801811821831841851861871881893 unmodified lines1931941951961971981991 unmodified line2012022032042052062073 unmodified lines2112122132142152162172182192202212222232242252262272282292302312322332 unmodified lines2362372382392402412422 unmodified lines2452462472482492502512522532543 unmodified lines2582592602612622632642652662672682692702712722734 unmodified lines2782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483492 unmodified lines3523533543553563573583593603 unmodified lines3643653663673683693703713723733743753763773783793803813823833843851 unmodified line3873883893903913923933943954 unmodified lines4004014024034044054061 unmodified line40840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744810 unmodified lines4594604614624634643 unmodified lines4684694704714724734744754764774 unmodified lines4824834844854864874884894904914924 unmodified lines4974984995005015025035045055065075085095105115125132 unmodified lines516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568389 unmodified lines9589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100442 unmodified lines1047104810491050105110521053105410551056105710581059106010611062142 unmodified lines1205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130534 unmodified linesclass UltimateTopcoderMCPEngine:"""ULTIMATE MCP Engine - Real Data + Advanced Intelligence"""def __init__(self):print("π Initializing ULTIMATE Topcoder Intelligence Engine...")self.base_url = "https://api.topcoder-dev.com/v6/mcp"1 unmodified lineself.is_connected = Falseself.mock_challenges = self._create_enhanced_fallback_challenges()print(f"β Loaded fallback system with {len(self.mock_challenges)} premium challenges")def _create_enhanced_fallback_challenges(self) -> List[Challenge]:return [Challenge(id="30174840",56 unmodified linesregistrants=24)]def parse_sse_response(self, sse_text: str) -> Dict[str, Any]:lines = sse_text.strip().split('\n')for line in lines:line = line.strip()4 unmodified linesexcept json.JSONDecodeError:passreturn Noneasync def initialize_connection(self) -> bool:if self.is_connected:return Trueheaders = {"Accept": "application/json, text/event-stream, */*","Accept-Language": "en-US,en;q=0.9",3 unmodified lines"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,11 unmodified lines}}}try:async with httpx.AsyncClient(timeout=10.0) as client:response = await client.post(1 unmodified linejson=init_request,headers=headers)if response.status_code == 200:response_headers = dict(response.headers)if 'mcp-session-id' in response_headers:1 unmodified lineself.is_connected = Trueprint(f"β Real MCP connection established: {self.session_id[:8]}...")return Trueexcept Exception as e:print(f"β οΈ MCP connection failed, using enhanced fallback: {e}")return Falseasync def call_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Optional[Dict]: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()),3 unmodified lines"arguments": arguments}}try:async with httpx.AsyncClient(timeout=30.0) as client:response = await client.post(1 unmodified linejson=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)3 unmodified linesjson_data = response.json()if "result" in json_data:return json_data["result"]except Exception:passreturn Nonedef convert_topcoder_challenge(self, tc_data: Dict) -> Challenge:challenge_id = str(tc_data.get('id', 'unknown'))title = tc_data.get('name', 'Topcoder Challenge')description = tc_data.get('description', 'Challenge description not available')technologies = []skills = tc_data.get('skills', [])for skill in skills:if isinstance(skill, dict) and 'name' in skill:technologies.append(skill['name'])if 'technologies' in tc_data:tech_list = tc_data['technologies']if isinstance(tech_list, list):2 unmodified linestechnologies.append(tech['name'])elif isinstance(tech, str):technologies.append(tech)total_prize = 0prize_sets = tc_data.get('prizeSets', [])for prize_set in prize_sets:2 unmodified linesfor 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"challenge_type = tc_data.get('type', 'Unknown')difficulty_mapping = {'First2Finish': 'Beginner','Code': 'Intermediate',3 unmodified lines'Bug Hunt': 'Beginner','Test Suites': 'Intermediate'}difficulty = difficulty_mapping.get(challenge_type, 'Intermediate')time_estimate = "Variable duration"registrants = tc_data.get('numOfRegistrants', 0)status = tc_data.get('status', '')if status == 'Completed':time_estimate = "Recently completed"elif status in ['Active', 'Draft']:time_estimate = "Active challenge"return Challenge(id=challenge_id,title=title,4 unmodified linestime_estimate=time_estimate,registrants=registrants)def extract_technologies_from_query(self, query: str) -> List[str]:tech_keywords = {'python', 'java', 'javascript', 'react', 'node', 'angular', 'vue','aws', 'docker', 'kubernetes', 'api', 'rest', 'graphql', 'sql','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','figma', 'ui/ux', 'design', 'testing', 'jest', 'hardhat', 'web3','fastapi', 'django', 'flask', 'redis', 'tensorflow', 'd3.js', 'chart.js'}query_lower = query.lower()found_techs = [tech for tech in tech_keywords if tech in query_lower]return found_techsasync def fetch_real_challenges(self,user_profile: UserProfile,query: str,limit: int = 30,status: str = None,prize_min: int = None,prize_max: int = None,challenge_type: str = None,track: str = None,sort_by: str = None,sort_order: str = None,) -> List[Challenge]:if not await self.initialize_connection():return []skill_keywords = self.extract_technologies_from_query(query + " " + " ".join(user_profile.skills + user_profile.interests))mcp_query = {"perPage": limit,}mcp_query["status"] = status if status else "Active"if prize_min is not None:mcp_query["totalPrizesFrom"] = prize_minif prize_max is not None:mcp_query["totalPrizesTo"] = prize_maxif challenge_type:mcp_query["type"] = challenge_typeif track:mcp_query["track"] = trackif skill_keywords:mcp_query["tags"] = skill_keywordsif query.strip():mcp_query["search"] = query.strip()mcp_query["sortBy"] = sort_by if sort_by else "overview.totalPrizes"mcp_query["sortOrder"] = sort_order if sort_order else "desc"result = await self.call_tool("query-tc-challenges", mcp_query)if not result:return []challenge_data_list = []if "structuredContent" in result:structured = result["structuredContent"]if isinstance(structured, dict) and "data" in structured:challenge_data_list = structured["data"]elif "data" in result:challenge_data_list = result["data"]elif "content" in result and len(result["content"]) > 0:content_item = result["content"][0]if isinstance(content_item, dict) and content_item.get("type") == "text":2 unmodified linesparsed_data = json.loads(text_content)if "data" in parsed_data:challenge_data_list = parsed_data["data"]except json.JSONDecodeError:passchallenges = []for item in challenge_data_list:if isinstance(item, dict):3 unmodified linesexcept Exception as e:print(f"Error converting challenge: {e}")continuereturn challengesdef calculate_advanced_compatibility_score(self, challenge: Challenge, user_profile: UserProfile, query: str) -> tuple:score = 0.0factors = []user_skills_lower = [skill.lower().strip() 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:exact_match_score = (skill_matches / len(challenge.technologies)) * 30coverage_bonus = min(skill_matches * 10, 10)skill_score = exact_match_score + coverage_bonuselse:skill_score = 30score += skill_scoreif skill_matches > 0:matched_skills = [t for t in challenge.technologies if t.lower() in user_skills_lower]factors.append(f"Strong match: uses your {', '.join(matched_skills[:2])} expertise")1 unmodified linefactors.append(f"Growth opportunity: learn {', '.join(challenge.technologies[:2])}")else:factors.append("Versatile challenge suitable for multiple skill levels")level_mapping = {'beginner': 1, 'intermediate': 2, 'advanced': 3}user_level_num = level_mapping.get(user_profile.experience_level.lower(), 2)challenge_level_num = level_mapping.get(challenge.difficulty.lower(), 2)level_diff = abs(user_level_num - challenge_level_num)if level_diff == 0:level_score = 304 unmodified lineselse:level_score = 5factors.append("Stretch challenge with significant learning curve")score += level_scorequery_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))1 unmodified linequery_score = min(query_matches / len(query_techs), 1.0) * 20else:query_score = 10if query_matches > 0:factors.append(f"Directly matches your interest in {', '.join(query_techs[:2])}")else:query_score = 10score += query_scoretry:prize_numeric = 0if challenge.prize.startswith('$'):prize_str = challenge.prize[1:].replace(',', '')prize_numeric = int(prize_str) if prize_str.isdigit() else 0prize_score = min(prize_numeric / 1000 * 2, 8)competition_bonus = 2 if 20 <= challenge.registrants <= 50 else 0market_score = prize_score + competition_bonusexcept:market_score = 5score += market_scorereturn min(score, 100.0), factorsdef get_user_insights(self, user_profile: UserProfile) -> Dict:skills = user_profile.skillslevel = user_profile.experience_leveltime_available = user_profile.time_availablefrontend_skills = ['react', 'javascript', 'css', 'html', 'vue', 'angular', 'typescript']backend_skills = ['python', 'java', 'node', 'fastapi', 'django', 'flask', 'php', 'ruby']data_skills = ['sql', 'postgresql', 'mongodb', 'redis', 'elasticsearch', 'tensorflow']devops_skills = ['docker', 'kubernetes', 'aws', 'azure', 'terraform', 'jenkins']design_skills = ['figma', 'ui/ux', 'design', 'prototyping', 'accessibility']blockchain_skills = ['solidity', 'web3', 'ethereum', 'blockchain', 'smart contracts', 'nft']user_skills_lower = [skill.lower() for skill in skills]frontend_count = sum(1 for skill in user_skills_lower if any(fs in skill for fs in frontend_skills))backend_count = sum(1 for skill in user_skills_lower if any(bs in skill for bs in backend_skills))data_count = sum(1 for skill in user_skills_lower if any(ds in skill for ds in data_skills))devops_count = sum(1 for skill in user_skills_lower if any(ds in skill for ds in devops_skills))design_count = sum(1 for skill in user_skills_lower if any(ds in skill for ds in design_skills))blockchain_count = sum(1 for skill in user_skills_lower if any(bs in skill for bs in blockchain_skills))if blockchain_count >= 2:profile_type = "Blockchain Developer"elif frontend_count >= 2 and backend_count >= 1:10 unmodified linesprofile_type = "DevOps Engineer"else:profile_type = "Versatile Developer"insights = {'profile_type': profile_type,'strengths': f"Strong {profile_type.lower()} with expertise in {', '.join(skills[:3]) if skills else 'multiple technologies'}",3 unmodified lines'time_optimization': f"With {time_available}, you can complete 1-2 medium challenges or 1 large project",'success_probability': self._calculate_success_probability(level, len(skills))}return insightsdef _suggest_growth_areas(self, user_skills: List[str], frontend: int, backend: int, data: int, devops: int, blockchain: int) -> str:suggestions = []if blockchain < 1 and (frontend >= 1 or backend >= 1):suggestions.append("blockchain and Web3 technologies")if devops < 1:4 unmodified linessuggestions.append("TypeScript for enhanced development")if backend >= 1 and "api" not in str(user_skills):suggestions.append("API design and microservices")if not suggestions:suggestions = ["AI/ML integration", "system design", "performance optimization"]return "Consider exploring " + ", ".join(suggestions[:3])def _get_market_trends(self, skills: List[str]) -> str:hot_skills = {'react': 'React dominates frontend with 75% job market share','python': 'Python leads in AI/ML and backend development growth',4 unmodified lines'ai': 'AI integration skills in highest demand for 2024','kubernetes': 'Container orchestration critical for enterprise roles'}for skill in skills:skill_lower = skill.lower()for hot_skill, trend in hot_skills.items():if hot_skill in skill_lower:return trendreturn "Full-stack and cloud skills show strongest market demand"def _calculate_success_probability(self, level: str, skill_count: int) -> str:base_score = {'beginner': 60, 'intermediate': 75, 'advanced': 85}.get(level.lower(), 70)skill_bonus = min(skill_count * 3, 15)total = base_score + skill_bonusif total >= 90:return f"{total}% - Outstanding success potential"elif total >= 80:2 unmodified linesreturn f"{total}% - Good probability of success"else:return f"{total}% - Consider skill development first"async def get_personalized_recommendations(self, user_profile: UserProfile, query: str = "",status: str = None, prize_min: int = None, prize_max: int = None,challenge_type: str = None, track: str = None,sort_by: str = None, sort_order: str = None,limit: int = 50) -> Dict[str, Any]:start_time = datetime.now()print(f"π Analyzing profile: {user_profile.skills} | Level: {user_profile.experience_level}")real_challenges = await self.fetch_real_challenges(user_profile=user_profile,query=query,limit=limit,status=status,prize_min=prize_min,prize_max=prize_max,challenge_type=challenge_type,track=track,sort_by=sort_by,sort_order=sort_order,)if real_challenges:challenges = real_challengesdata_source = "π₯ REAL Topcoder MCP Server (4,596+ challenges)"print(f"π Using {len(challenges)} REAL Topcoder challenges!")else:challenges = self.mock_challengesdata_source = "β¨ Enhanced Intelligence Engine (Premium Dataset)"print(f"β‘ Using {len(challenges)} premium challenges with advanced algorithms")scored_challenges = []for challenge in challenges:score, factors = self.calculate_advanced_compatibility_score(challenge, user_profile, query)challenge.compatibility_score = scorechallenge.rationale = f"Match: {score:.0f}%. " + ". ".join(factors[:2]) + "."scored_challenges.append(challenge)scored_challenges.sort(key=lambda x: x.compatibility_score, reverse=True)recommendations = scored_challenges[:5]processing_time = (datetime.now() - start_time).total_seconds()query_techs = self.extract_technologies_from_query(query)avg_score = sum(c.compatibility_score for c in challenges) / len(challenges) if challenges else 0print(f"β Generated {len(recommendations)} recommendations in {processing_time:.3f}s:")for i, rec in enumerate(recommendations, 1):print(f" {i}. {rec.title} - {rec.compatibility_score:.0f}% compatibility")return {"recommendations": [asdict(rec) for rec in recommendations],"insights": {389 unmodified lines</div>"""async def get_ultimate_recommendations_async(skills_input: str, experience_level: str, time_available: str, interests: str,status: str, prize_min: int, prize_max: int, challenge_type: str, track: str,sort_by: str, sort_order: str) -> Tuple[str, str]:# ...input validation, parsing...skills = [skill.strip() for skill in skills_input.split(',') if skill.strip()]user_profile = UserProfile(skills=skills,experience_level=experience_level,time_available=time_available,interests=[interests] if interests else [])# Pass all new filter params to get_personalized_recommendationsrecommendations_data = await intelligence_engine.get_personalized_recommendations(user_profile,interests,status=status,prize_min=prize_min,prize_max=prize_max,challenge_type=challenge_type,track=track,sort_by=sort_by,sort_order=sort_order,limit=50)insights = intelligence_engine.get_user_insights(user_profile)recommendations = recommendations_data["recommendations"]insights_data = recommendations_data["insights"]real_challenges = await intelligence_engine.fetch_real_challenges(user_profile=user_profile,query=interests,limit=50,status=status,prize_min=prize_min,prize_max=prize_max,challenge_type=challenge_type,track=track,sort_by=sort_by,sort_order=sort_order,)# Format results with enhanced stylingif recommendations:# Success header with data source info42 unmodified linesprint(f"β Error processing ULTIMATE request: {str(e)}")return error_msg, ""def get_ultimate_recommendations_sync(skills_input: str, experience_level: str, time_available: str, interests: str,status: str, prize_min: int, prize_max: int, challenge_type: str, track: str,sort_by: str, sort_order: str) -> Tuple[str, str]:return asyncio.run(get_ultimate_recommendations_async(skills_input, experience_level, time_available, interests,status, prize_min, prize_max, challenge_type, track,sort_by, sort_order))def run_ultimate_performance_test():"""ULTIMATE comprehensive system performance test"""results = []142 unmodified lineswith gr.TabItem("π― ULTIMATE Recommendations", elem_id="ultimate-recommendations"):gr.Markdown("### π AI-Powered Challenge Discovery with Real MCP Data")# ... Inside create_ultimate_interface() ...with gr.Row():with gr.Column(scale=1):gr.Markdown("**π€ Tell the AI about yourself and filter challenges:**")skills_input = gr.Textbox(label="π οΈ Your Skills & Technologies",placeholder="Python, React, JavaScript, AWS, Docker, Blockchain, UI/UX...",lines=3,value="Python, JavaScript, React")experience_level = gr.Dropdown(choices=["Beginner", "Intermediate", "Advanced"],label="π Experience Level",value="Intermediate")time_available = gr.Dropdown(choices=["2-4 hours", "4-8 hours", "8+ hours"],label="β° Time Available",value="4-8 hours")interests = gr.Textbox(label="π― Current Interests & Goals",placeholder="web development, blockchain, AI/ML, cloud computing, mobile apps...",lines=3,value="web development, cloud computing")# --- NEW FILTERS BELOW ---status_dropdown = gr.Dropdown(choices=["Active", "Completed", "Draft", "Cancelled"],label="Challenge Status",value="Active")prize_min = gr.Number(label="Minimum Prize ($)",value=0)prize_max = gr.Number(label="Maximum Prize ($)",value=10000)type_dropdown = gr.Dropdown(choices=["", "Code", "First2Finish", "UI Prototype Competition", "Bug Hunt", "Test Suites"],label="Challenge Type",value="")track_dropdown = gr.Dropdown(choices=["", "DEVELOPMENT", "DESIGN", "DATA_SCIENCE", "QA"],label="Track",value="")sort_by_dropdown = gr.Dropdown(choices=["overview.totalPrizes", "numOfRegistrants", "endDate", "startDate"],label="Sort By",value="overview.totalPrizes")sort_order_dropdown = gr.Dropdown(choices=["desc", "asc"],label="Sort Order",value="desc")ultimate_recommend_btn = gr.Button("π Get My ULTIMATE Recommendations",variant="primary",size="lg",elem_classes="ultimate-btn")# ...Tips markdown...with gr.Column(scale=2):ultimate_insights_output = gr.HTML(label="π§ Your Intelligence Profile", visible=True)ultimate_recommendations_output = gr.HTML(label="π Your ULTIMATE Recommendations", visible=True)# --- Connect the ULTIMATE recommendation system with new inputs ---ultimate_recommend_btn.click(get_ultimate_recommendations_sync,inputs=[skills_input,experience_level,time_available,interests,status_dropdown,prize_min,prize_max,type_dropdown,track_dropdown,sort_by_dropdown,sort_order_dropdown],outputs=[ultimate_recommendations_output, ultimate_insights_output])
app.py+222-219