Upload app.py
Browse files233 unmodified lines2342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923 unmodified lines39639739839940040140240340440540640740840941041141241341433 unmodified lines448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535152 unmodified lines6886896906916926936946956966976986997007017027037 unmodified lines7117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547556 unmodified lines762763764765766767768636 unmodified lines140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476206 unmodified lines16831684168516861687168816896 unmodified lines16961697169816991700170117022 unmodified lines17051706170717081709171017111712171317141715233 unmodified linesreturn Nonedef convert_topcoder_challenge(self, tc_data: Dict) -> Challenge:"""FIXED: Debug what's actually in the MCP challenge data"""try:print(f"\nπ === CONVERTING CHALLENGE DATA ===")print(f"π Raw challenge keys: {list(tc_data.keys())}")# Show first few fields for debuggingfor key, value in list(tc_data.items())[:10]: # Show first 10 fieldsif isinstance(value, str):print(f" {key}: '{value[:100]}{'...' if len(str(value)) > 100 else ''}'")elif isinstance(value, (int, float, bool)):print(f" {key}: {value}")elif isinstance(value, list):print(f" {key}: list with {len(value)} items")if len(value) > 0 and isinstance(value[0], dict):print(f" First item keys: {list(value[0].keys())}")elif isinstance(value, dict):print(f" {key}: dict with keys {list(value.keys())}")else:print(f" {key}: {type(value)}")# Extract basic fields with debuggingchallenge_id = str(tc_data.get('id', tc_data.get('challengeId', 'unknown')))print(f"π Extracted ID: {challenge_id}")title = tc_data.get('name', tc_data.get('title', tc_data.get('challengeName', 'Topcoder Challenge')))print(f"π Extracted title: {title}")description = tc_data.get('description', tc_data.get('overview', tc_data.get('summary', 'Challenge description not available')))print(f"π Extracted description: {description[:100]}...")# Extract technologies/skills with detailed debuggingtechnologies = []print(f"π§ Looking for technologies...")# Check skills fieldskills = tc_data.get('skills', [])print(f" Skills field: {skills}")if skills:for skill in skills:if isinstance(skill, dict):skill_name = skill.get('name', skill.get('skillName', ''))if skill_name:technologies.append(skill_name)print(f" Added skill: {skill_name}")elif isinstance(skill, str):technologies.append(skill)print(f" Added skill: {skill}")# Check technologies fieldtech_field = tc_data.get('technologies', [])print(f" Technologies field: {tech_field}")if tech_field:for tech in tech_field:if isinstance(tech, dict):tech_name = tech.get('name', tech.get('technologyName', ''))if tech_name:technologies.append(tech_name)print(f" Added tech: {tech_name}")elif isinstance(tech, str):technologies.append(tech)print(f" Added tech: {tech}")# Check tags fieldtags = tc_data.get('tags', [])print(f" Tags field: {tags}")if tags:for tag in tags[:3]: # Limit to 3 tagsif isinstance(tag, str):technologies.append(tag)print(f" Added tag: {tag}")# If no technologies found, try other fieldsif not technologies:print(f" No technologies found, checking other fields...")track = tc_data.get('track', tc_data.get('trackName', ''))if track:technologies.append(track)print(f" Added track: {track}")challenge_type = tc_data.get('type', tc_data.get('challengeType', ''))if challenge_type:technologies.append(challenge_type)print(f" Added type: {challenge_type}")# Remove duplicatestechnologies = list(set(technologies))print(f"π οΈ Final technologies: {technologies}")# Extract prize information with debuggingprint(f"π° Looking for prize information...")total_prize = 0# Check prizeSetsprize_sets = tc_data.get('prizeSets', [])print(f" Prize sets: {prize_sets}")if prize_sets:for prize_set in prize_sets:if isinstance(prize_set, dict) and prize_set.get('type') == 'placement':prizes = prize_set.get('prizes', [])for prize in prizes:if isinstance(prize, dict) and prize.get('type') == 'USD':prize_value = prize.get('value', 0)total_prize += prize_valueprint(f" Added prize: ${prize_value}")# Check overview fieldif total_prize == 0:overview = tc_data.get('overview', {})if isinstance(overview, dict):overview_prize = overview.get('totalPrizes', 0)if overview_prize:total_prize = overview_prizeprint(f" Found overview prize: ${total_prize}")# Check direct prize fieldif total_prize == 0:direct_prize = tc_data.get('prize', tc_data.get('totalPrize', 0))if direct_prize:total_prize = direct_prizeprint(f" Found direct prize: ${total_prize}")prize = f"${total_prize:,}" if total_prize > 0 else "Merit-based"print(f"π° Final prize: {prize}")# Extract other fieldschallenge_type = tc_data.get('type', tc_data.get('challengeType', 'Challenge'))difficulty_mapping = {'First2Finish': 'Beginner','Code': 'Intermediate','Assembly Competition': 'Advanced','UI Prototype Competition': 'Intermediate','Copilot Posting': 'Beginner','Bug Hunt': 'Beginner','Test Suites': 'Intermediate','Challenge': 'Intermediate'}difficulty = difficulty_mapping.get(challenge_type, 'Intermediate')print(f"π Difficulty: {difficulty} (from type: {challenge_type})")registrants = tc_data.get('numOfRegistrants', tc_data.get('registrants', 0))print(f"π₯ Registrants: {registrants}")status = tc_data.get('status', 'Unknown')if status == 'Completed':time_estimate = "Recently completed"elif status in ['Active', 'Draft']:time_estimate = "Active challenge"else:time_estimate = "Variable duration"print(f"β° Time estimate: {time_estimate} (from status: {status})")# Create challenge objectchallenge = Challenge(id=challenge_id,title=title,description=description[:300] + "..." if len(description) > 300 else description,3 unmodified linestime_estimate=time_estimate,registrants=registrants)print(f"β Created challenge: {challenge.title}")print(f" Technologies: {challenge.technologies}")print(f" Prize: {challenge.prize}")print(f" Registrants: {challenge.registrants}")print(f"π === CHALLENGE CONVERSION COMPLETE ===\n")return challengeexcept Exception as e:print(f"β Error converting challenge data: {e}")print(f"Raw data keys: {list(tc_data.keys()) if isinstance(tc_data, dict) else 'Not a dict'}")# Return a basic challenge object as fallbackreturn Challenge(id=str(tc_data.get('id', 'unknown')),title=str(tc_data.get('name', 'Challenge')),33 unmodified linessort_by: str = None,sort_order: str = None,) -> List[Challenge]:"""FIXED: Guaranteed to return real challenges when MCP works"""print(f"π Fetching REAL challenges (limit: {limit})")print(f"π― Query: '{query}' | Skills: {user_profile.skills}")# Always try to connectconnection_success = await self.initialize_connection()if not connection_success:print("β Could not establish MCP connection")return []# Build simple query that we KNOW works from debugmcp_query = {"perPage": min(limit, 20)}# Add search term if providedif query.strip():mcp_query["search"] = query.strip()# Add status filterif status and status != "":mcp_query["status"] = statusprint(f"π§ MCP Query: {mcp_query}")# Call the MCP tool (we know this works from debug)result = await self.call_tool("query-tc-challenges", mcp_query)if not result:print("β No result from MCP tool call")return []print(f"π Got MCP result with keys: {list(result.keys()) if isinstance(result, dict) else 'Not dict'}")# Extract challenge data (we know it's in structuredContent.data from debug)challenge_data_list = []if isinstance(result, dict):# Primary location: structuredContent.dataif "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.data")# Fallback: direct data fieldelif "data" in result:challenge_data_list = result["data"]print(f"β Found {len(challenge_data_list)} challenges in data field")if not challenge_data_list:print("β No challenge data found in response")return []print(f"π― Processing {len(challenge_data_list)} raw challenges...")# Convert to Challenge objectschallenges = []for i, item in enumerate(challenge_data_list):if isinstance(item, dict):try:challenge = self.convert_topcoder_challenge(item)challenges.append(challenge)# Show details for first challengeif i == 0:print(f"π Sample: {challenge.title} | {challenge.prize} | {challenge.technologies}")except Exception as e:print(f"β οΈ Error converting challenge {i}: {e}")# Don't let one bad challenge break everythingcontinueelse:print(f"β οΈ Unexpected challenge format at index {i}: {type(item)}")print(f"π SUCCESSFULLY converted {len(challenges)} REAL challenges!")# IMPORTANT: Always return challenges if we got any data at allif len(challenges) > 0:return challengeselse:print("β No challenges could be converted from raw data")return []def calculate_advanced_compatibility_score(self, challenge: Challenge, user_profile: UserProfile, query: str) -> tuple:score = 0.0152 unmodified linessort_by: str = None, sort_order: str = None,limit: int = 50) -> Dict[str, Any]:"""FIXED: Debug the actual recommendation flow"""start_time = datetime.now()print(f"\nπ― === STARTING RECOMMENDATION REQUEST ===")print(f"π― User skills: {user_profile.skills}")print(f"π― Query: '{query}'")print(f"π― Status filter: {status}")print(f"π― Limit: {limit}")# FIXED: Try to get real challenges with detailed debuggingprint(f"\nπ Step 1: Attempting to fetch REAL challenges...")real_challenges = await self.fetch_real_challenges(user_profile=user_profile,query=query,7 unmodified linessort_order=sort_order,)print(f"π Step 2: fetch_real_challenges returned {len(real_challenges)} challenges")# Determine data source and challenges to useif real_challenges and len(real_challenges) > 0:challenges = real_challengesdata_source = f"π₯ REAL Topcoder MCP Server ({len(challenges)} live challenges)"print(f"β Step 3: Using {len(challenges)} REAL MCP challenges!")# Show sample challenge detailsif challenges:sample = challenges[0]print(f"π Sample real challenge: {sample.title} | {sample.prize} | {sample.technologies}")else:challenges = self.mock_challengesdata_source = "β‘ Enhanced Intelligence Engine (Premium Dataset)"print(f"β οΈ Step 3: No real challenges returned, using {len(challenges)} fallback challenges")print(f"π Debug: Why no real challenges? Check fetch_real_challenges output above")# Score and rank challengesprint(f"\nπ§ Step 4: Scoring {len(challenges)} challenges...")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"β Step 5: Generated {len(recommendations)} recommendations in {processing_time:.3f}s")print(f"π Top recommendation: {recommendations[0].title} ({recommendations[0].compatibility_score:.0f}%)")print(f"π Data source being reported: {data_source}")print(f"π― === RECOMMENDATION REQUEST COMPLETE ===\n")return {"recommendations": [asdict(rec) for rec in recommendations],"insights": {6 unmodified lines"session_active": bool(self.session_id),"mcp_connected": self.is_connected,"algorithm_version": "Advanced Multi-Factor v2.0","topcoder_total": f"{len(challenges)} challenges analyzed"}}636 unmodified linesreturn "\n".join(results)def debug_mcp_queries():"""Debug specific MCP queries to see what works"""results = []results.append("π DEBUG MCP QUERY TESTING")results.append("=" * 40)async def test_different_queries():# Test queries that should work vs ones that don'ttest_queries = [("AI", {"search": "AI", "perPage": 5}),("Python", {"search": "Python", "perPage": 5}),("React", {"search": "React", "perPage": 5}),("JavaScript", {"search": "JavaScript", "perPage": 5}),("AI with tags", {"tags": ["AI"], "perPage": 5}),("Python with tags", {"tags": ["Python"], "perPage": 5}),("Simple empty", {"perPage": 5}),("Status only", {"status": "Active", "perPage": 5}),("AI minimal", {"search": "ai", "perPage": 3})]for query_name, query_params in test_queries:results.append(f"\nπ§ͺ Testing: {query_name}")results.append(f"π Parameters: {query_params}")try:result = await intelligence_engine.call_tool("query-tc-challenges", query_params)if result:results.append(f"β Got response!")if isinstance(result, dict):results.append(f"π Response keys: {list(result.keys())}")# Check for datachallenge_count = 0if "structuredContent" in result and "data" in result["structuredContent"]:challenge_count = len(result["structuredContent"]["data"])elif "data" in result:challenge_count = len(result["data"])results.append(f"π― Challenge count: {challenge_count}")if challenge_count > 0:results.append(f"π₯ SUCCESS! {query_name} returned {challenge_count} challenges")else:results.append(f"β οΈ {query_name} returned empty data")else:results.append(f"π Response type: {type(result)}")else:results.append(f"β No response for {query_name}")except Exception as e:results.append(f"β Error testing {query_name}: {str(e)}")# Run the async testtry:asyncio.run(test_different_queries())except Exception as e:results.append(f"β Test failed: {str(e)}")results.append("\nπ― ANALYSIS:")results.append("This will show which query patterns work with the real MCP server.")results.append("If only 'AI' queries work, it might be a server-side data issue.")results.append("If multiple queries work, it might be our parsing logic.")return "\n".join(results)def create_ultimate_interface():"""Create the ULTIMATE Gradio interface combining all features"""print("π¨ Creating ULTIMATE Gradio interface...")206 unmodified linesoutputs=[enhanced_chatbot, enhanced_chat_input])# Tab 3: FIXED ULTIMATE Performance - ALL OPTIONS RESTORED + DEBUGwith gr.TabItem("β‘ ULTIMATE Performance"):gr.Markdown("""### π§ͺ ULTIMATE System Performance & Real MCP Integration6 unmodified linesultimate_test_btn = gr.Button("π§ͺ Run ULTIMATE Performance Test", variant="secondary", size="lg", elem_classes="ultimate-btn")quick_benchmark_btn = gr.Button("β‘ Quick Benchmark", variant="secondary")mcp_status_btn = gr.Button("π₯ Check Real MCP Status", variant="secondary")debug_queries_btn = gr.Button("π Debug MCP Queries", variant="secondary")with gr.Column():ultimate_test_output = gr.Textbox(2 unmodified linesshow_label=True)# FIXED: Connect all test functions including debugultimate_test_btn.click(run_ultimate_performance_test, outputs=ultimate_test_output)quick_benchmark_btn.click(quick_benchmark, outputs=ultimate_test_output)mcp_status_btn.click(check_mcp_status, outputs=ultimate_test_output)debug_queries_btn.click(debug_mcp_queries, outputs=ultimate_test_output)# Tab 4: ULTIMATE About & Documentationwith gr.TabItem("βΉοΈ ULTIMATE About"):233 unmodified lines2342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912923 unmodified lines29629729829930030130230330433 unmodified lines338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431152 unmodified lines5845855865875885895905915925937 unmodified lines6016026036046056066076086096106116126136146156166176186196206216226236246256266276286296 unmodified lines636637638639640641642636 unmodified lines127912801281128212831284206 unmodified lines14911492149314941495149614976 unmodified lines1504150515061507150815092 unmodified lines1512151315141515151615171518151915201521233 unmodified linesreturn Nonedef convert_topcoder_challenge(self, tc_data: Dict) -> Challenge:"""Enhanced data conversion from Topcoder MCP response"""try: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):for tech in tech_list:if isinstance(tech, dict) and 'name' in tech:technologies.append(tech['name'])elif isinstance(tech, str):technologies.append(tech)total_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"challenge_type = tc_data.get('type', 'Unknown')difficulty_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_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,description=description[:300] + "..." if len(description) > 300 else description,3 unmodified linestime_estimate=time_estimate,registrants=registrants)except Exception as e:print(f"β Error converting challenge: {e}")return Challenge(id=str(tc_data.get('id', 'unknown')),title=str(tc_data.get('name', 'Challenge')),33 unmodified linessort_by: str = None,sort_order: str = None,) -> List[Challenge]:"""FIXED: More aggressive real challenge fetching"""# Always try to connectprint(f"π Attempting to fetch REAL challenges (limit: {limit})")connection_success = await self.initialize_connection()if not connection_success:print("β Could not establish MCP connection, using fallback")return []# Build comprehensive query parametersskill_keywords = self.extract_technologies_from_query(query + " " + " ".join(user_profile.skills + user_profile.interests))mcp_query = {"perPage": limit,}# Add filters based on user inputif status:mcp_query["status"] = statuselse:mcp_query["status"] = "Active" # Default to activeif 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()# Set sortingmcp_query["sortBy"] = sort_by if sort_by else "overview.totalPrizes"mcp_query["sortOrder"] = sort_order if sort_order else "desc"print(f"π§ MCP Query parameters: {mcp_query}")# Call the MCP toolresult = await self.call_tool("query-tc-challenges", mcp_query)if not result:print("β No result from MCP tool call")return []print(f"π Raw MCP result type: {type(result)}")if isinstance(result, dict):print(f"π MCP result keys: {list(result.keys())}")# FIXED: Better response parsing - handle multiple formatschallenge_data_list = []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")elif "data" in result:challenge_data_list = result["data"]print(f"β Found {len(challenge_data_list)} challenges in 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":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 parsed content")except json.JSONDecodeError:passchallenges = []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 challenges")return challengesdef calculate_advanced_compatibility_score(self, challenge: Challenge, user_profile: UserProfile, query: str) -> tuple:score = 0.0152 unmodified linessort_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}")# FIXED: More aggressive real data fetchingreal_challenges = await self.fetch_real_challenges(user_profile=user_profile,query=query,7 unmodified linessort_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": {6 unmodified lines"session_active": bool(self.session_id),"mcp_connected": self.is_connected,"algorithm_version": "Advanced Multi-Factor v2.0","topcoder_total": "4,596+ live challenges" if real_challenges else "Premium dataset"}}636 unmodified linesreturn "\n".join(results)def create_ultimate_interface():"""Create the ULTIMATE Gradio interface combining all features"""print("π¨ Creating ULTIMATE Gradio interface...")206 unmodified linesoutputs=[enhanced_chatbot, enhanced_chat_input])# Tab 3: FIXED ULTIMATE Performance - ALL OPTIONS RESTOREDwith gr.TabItem("β‘ ULTIMATE Performance"):gr.Markdown("""### π§ͺ ULTIMATE System Performance & Real MCP Integration6 unmodified linesultimate_test_btn = gr.Button("π§ͺ Run ULTIMATE Performance Test", variant="secondary", size="lg", elem_classes="ultimate-btn")quick_benchmark_btn = gr.Button("β‘ Quick Benchmark", variant="secondary")mcp_status_btn = gr.Button("π₯ Check Real MCP Status", variant="secondary")with gr.Column():ultimate_test_output = gr.Textbox(2 unmodified linesshow_label=True)# FIXED: Connect all test functionsultimate_test_btn.click(run_ultimate_performance_test, outputs=ultimate_test_output)quick_benchmark_btn.click(quick_benchmark, outputs=ultimate_test_output)mcp_status_btn.click(check_mcp_status, outputs=ultimate_test_output)# Tab 4: ULTIMATE About & Documentationwith gr.TabItem("βΉοΈ ULTIMATE About"):
app.py+105-299