Upload app.py
Browse files123456176 unmodified lines1831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252266 unmodified lines2332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782793 unmodified lines28328428528628728828929029129229329429529629729829930030130230330430530630730830972 unmodified lines38238338438538638738838939039139239339439539639739839928 unmodified lines428429430431432433434"""FINAL Topcoder Challenge Intelligence AssistantWith REAL MCP Integration - Ready for Production"""import asyncioimport httpx176 unmodified linesreturn 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', [])6 unmodified linesprize = 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 []3 unmodified linesif 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"""72 unmodified linesreturn 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)"28 unmodified lines"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}}1234567176 unmodified lines1841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172186 unmodified lines2252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682693 unmodified lines27327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331472 unmodified lines38738838939039139239339439539639739839940040140240340440528 unmodified lines434435436437438439440441"""FINAL Topcoder Challenge Intelligence AssistantWith REAL MCP Integration - Ready for ProductionFIXED: Now uses structuredContent for real challenge data"""import asyncioimport httpx176 unmodified linesreturn Nonedef convert_topcoder_challenge(self, tc_data: Dict) -> Challenge:"""Convert real Topcoder challenge data to Challenge object - FIXED VERSION"""# Extract real fields from Topcoder data structurechallenge_id = str(tc_data.get('id', 'unknown'))# Topcoder uses 'name' field for challenge titletitle = tc_data.get('name', 'Topcoder Challenge')# Descriptiondescription = 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):for tech in tech_list:if isinstance(tech, dict) and 'name' in tech:technologies.append(tech['name'])elif isinstance(tech, str):technologies.append(tech)# Calculate total prize from prizeSetstotal_prize = 0prize_sets = tc_data.get('prizeSets', [])6 unmodified linesprize = f"${total_prize:,}" if total_prize > 0 else "Merit-based"# Map challenge type to difficultychallenge_type = tc_data.get('type', 'Unknown')type_id = tc_data.get('typeId', '')# Topcoder difficulty mappingdifficulty_mapping = {'First2Finish': 'Beginner','Code': 'Intermediate','Assembly Competition': 'Advanced','UI Prototype Competition': 'Intermediate','Copilot Posting': 'Beginner','Bug Hunt': 'Beginner','Test Suites': 'Intermediate'}difficulty = difficulty_mapping.get(challenge_type, 'Intermediate')# Time estimatetime_estimate = "Variable duration"# Check status and datesstatus = 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,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 - FIXED VERSION"""if not await self.initialize_connection():return []3 unmodified linesif not result:return []# ๐ฏ THE FIX: Use structuredContent instead of content!challenge_data_list = []# Method 1: Use structuredContent (already parsed JSON)if "structuredContent" in result:structured = result["structuredContent"]if isinstance(structured, dict) and "data" in structured:challenge_data_list = structured["data"]print(f"โ Found {len(challenge_data_list)} challenges in structuredContent")# Method 2: Fallback to parsing content[0]['text']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":try:text_content = content_item.get("text", "")parsed_data = json.loads(text_content)if "data" in parsed_data:challenge_data_list = parsed_data["data"]print(f"โ Found {len(challenge_data_list)} challenges in content text")except json.JSONDecodeError:pass# Convert to Challenge objectschallenges = []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}")continueprint(f"๐ Successfully converted {len(challenges)} real Topcoder challenges!")return challengesdef extract_technologies_from_query(self, query: str) -> List[str]:"""Extract technology keywords from user query"""72 unmodified linesreturn min(score, 1.0), factorsasync def get_personalized_recommendations(self, user_profile: UserProfile, query: str = "") -> Dict[str, Any]:"""Get personalized recommendations using REAL Topcoder data - FIXED VERSION"""start_time = datetime.now()# Fetch REAL challengesreal_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 mock datachallenges = self.mock_challengesdata_source = "Enhanced Mock Data (MCP unavailable)"28 unmodified lines"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,"topcoder_total": "4,596+ live challenges" if real_challenges else "Mock data"}}
app.py+73-66