Upload app.py
Browse files337 unmodified lines338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431847 unmodified lines127912801281128212831284206 unmodified lines14911492149314941495149614976 unmodified lines1504150515061507150815092 unmodified lines1512151315141515151615171518151915201521337 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.0847 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"):337 unmodified lines338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470847 unmodified lines131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389206 unmodified lines15961597159815991600160116026 unmodified lines16091610161116121613161416152 unmodified lines16181619162016211622162316241625162616271628337 unmodified linessort_by: str = None,sort_order: str = None,) -> List[Challenge]:"""FIXED: Debug version - shows exactly what MCP is doing"""# Always try to connectprint(f"π Attempting to fetch REAL challenges (limit: {limit})")print(f"π― Query: '{query}' | Skills: {user_profile.skills}")connection_success = await self.initialize_connection()if not connection_success:print("β Could not establish MCP connection, using fallback")return []# Try multiple query strategies to see what worksquery_strategies = []# Strategy 1: Simple query with minimal parameterssimple_query = {"perPage": min(limit, 20)}if query.strip():simple_query["search"] = query.strip()query_strategies.append(("Simple Search", simple_query))# Strategy 2: Skills-based queryskill_keywords = self.extract_technologies_from_query(query + " " + " ".join(user_profile.skills + user_profile.interests))if skill_keywords:skills_query = {"perPage": min(limit, 20)}skills_query["tags"] = skill_keywords[:3] # Limit to 3 skillsquery_strategies.append(("Skills Query", skills_query))# Strategy 3: Your comprehensive querycomprehensive_query = {"perPage": min(limit, 20)}if status:comprehensive_query["status"] = statusif query.strip():comprehensive_query["search"] = query.strip()if sort_by:comprehensive_query["sortBy"] = sort_byif sort_order:comprehensive_query["sortOrder"] = sort_orderquery_strategies.append(("Comprehensive", comprehensive_query))# Try each strategy until one worksfor strategy_name, mcp_query in query_strategies:print(f"\nπ§ͺ Trying {strategy_name} strategy:")print(f"π§ Query parameters: {mcp_query}")# Call the MCP toolresult = await self.call_tool("query-tc-challenges", mcp_query)if not result:print(f"β {strategy_name} failed - no result")continueprint(f"π {strategy_name} result type: {type(result)}")if isinstance(result, dict):print(f"π Result keys: {list(result.keys())}")# Show first few characters of each field for debuggingfor key, value in result.items():if isinstance(value, str):print(f" {key}: {str(value)[:100]}...")elif isinstance(value, dict):print(f" {key}: dict with keys {list(value.keys())}")elif isinstance(value, list):print(f" {key}: list with {len(value)} items")else:print(f" {key}: {type(value)}")# Try to parse the responsechallenge_data_list = []# Check all possible data locationsdata_sources = [("structuredContent.data", result.get("structuredContent", {}).get("data", [])),("data", result.get("data", [])),("content[0].text", None), # Will handle separately("result", result if isinstance(result, list) else [])]for source_name, data in data_sources:if data and isinstance(data, list) and len(data) > 0:challenge_data_list = dataprint(f"β Found {len(challenge_data_list)} challenges in {source_name}")break# Special handling for content fieldif not challenge_data_list and "content" in result:content = result["content"]if isinstance(content, list) and len(content) > 0:content_item = content[0]if isinstance(content_item, dict) and content_item.get("type") == "text":try:text_content = content_item.get("text", "")print(f"π Content text preview: {text_content[:200]}...")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 as e:print(f"β Failed to parse content JSON: {e}")if challenge_data_list:print(f"π― Sample challenge data keys: {list(challenge_data_list[0].keys()) if challenge_data_list else 'None'}")# Convert challengeschallenges = []for i, item in enumerate(challenge_data_list):if isinstance(item, dict):try:challenge = self.convert_topcoder_challenge(item)challenges.append(challenge)if i == 0: # Show first challenge detailsprint(f"π First challenge: {challenge.title} | {challenge.prize} | {challenge.technologies}")except Exception as e:print(f"β Error converting challenge {i}: {e}")continueif challenges:print(f"π SUCCESS with {strategy_name}! Converted {len(challenges)} REAL challenges")return challengeselse:print(f"β {strategy_name} - no challenges converted")else:print(f"β {strategy_name} - no challenge data found")print("β All strategies failed - no real MCP data retrieved")return []def calculate_advanced_compatibility_score(self, challenge: Challenge, user_profile: UserProfile, query: str) -> tuple:score = 0.0847 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"):
app.py+179-72