Upload app.py
Browse files123456789101114 unmodified lines262728293031323334353637381 unmodified line4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382 unmodified lines2412422432442452462472482492502512522532542555 unmodified lines2612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303312 unmodified lines334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399"""Real MCP Integration - Replace Mock Data with Live Topcoder MCPThis replaces your SimpleIntelligenceEngine with real MCP integration"""import asyncioimport httpximport jsonimport loggingfrom typing import List, Dict, Any, Optionalfrom dataclasses import dataclass, asdictfrom datetime import datetime, timedelta14 unmodified linescompatibility_score: float = 0.0rationale: str = ""@dataclassclass Skill:name: strcategory: strdescription: strrelevance_score: float = 0.0@dataclassclass UserProfile:skills: List[str]1 unmodified linetime_available: strinterests: List[str]class RealMCPIntelligenceEngine:"""Production MCP Integration - Real Topcoder Data"""def __init__(self):self.mcp_url = "https://api.topcoder-dev.com/v6/mcp"self.session_id = Noneself.is_connected = Falseself.challenges_cache = {}self.skills_cache = {}self.cache_expiry = None# Initialize connectionasyncio.create_task(self.initialize_connection())async def initialize_connection(self):"""Initialize MCP connection and authenticate if needed"""try:async with httpx.AsyncClient(timeout=30.0) as client:# Step 1: Try initializationinit_request = {"jsonrpc": "2.0","id": 1,"method": "initialize","params": {"protocolVersion": "2024-11-05","capabilities": {"roots": {"listChanged": True},"sampling": {}},"clientInfo": {"name": "topcoder-intelligence-assistant","version": "1.0.0"}}}headers = {"Content-Type": "application/json","Accept": "application/json, text/event-stream"}response = await client.post(f"{self.mcp_url}/mcp",json=init_request,headers=headers)if response.status_code == 200:result = response.json()if "result" in result:self.is_connected = Truelogger.info("β MCP Connection established")# Extract session info if providedserver_info = result["result"].get("serverInfo", {})if "sessionId" in server_info:self.session_id = server_info["sessionId"]logger.info(f"π Session ID obtained: {self.session_id[:10]}...")return Truelogger.warning(f"β οΈ MCP initialization failed: {response.status_code}")return Falseexcept Exception as e:logger.error(f"β MCP connection failed: {e}")return Falseasync def call_mcp_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Optional[Dict]:"""Call an MCP tool with proper error handling"""if not self.is_connected:await self.initialize_connection()try:async with httpx.AsyncClient(timeout=60.0) as client:request_data = {"jsonrpc": "2.0","id": datetime.now().timestamp(),"method": "tools/call","params": {"name": tool_name,"arguments": arguments}}headers = {"Content-Type": "application/json","Accept": "application/json"}# Add session ID if we have oneif self.session_id:headers["X-Session-ID"] = self.session_idresponse = await client.post(f"{self.mcp_url}/mcp",json=request_data,headers=headers)if response.status_code == 200:result = response.json()if "result" in result:return result["result"]elif "error" in result:logger.error(f"MCP tool error: {result['error']}")return Noneelse:logger.error(f"MCP tool call failed: {response.status_code} - {response.text}")return Noneexcept Exception as e:logger.error(f"MCP tool call exception: {e}")return Noneasync def fetch_challenges(self, limit: int = 50, technologies: List[str] = None) -> List[Challenge]:"""Fetch real challenges from Topcoder MCP"""# Check cache firstcache_key = f"challenges_{limit}_{technologies}"if (self.cache_expiry and datetime.now() < self.cache_expiry andcache_key in self.challenges_cache):return self.challenges_cache[cache_key]arguments = {"limit": limit}if technologies:arguments["technologies"] = technologiesresult = await self.call_mcp_tool("query-tc-challenges", arguments)if result and "content" in result:challenges_data = result["content"]challenges = []for item in challenges_data:if isinstance(item, dict):challenge = Challenge(id=str(item.get("id", "")),title=item.get("title", "Unknown Challenge"),description=item.get("description", "")[:200] + "...",technologies=item.get("technologies", []),difficulty=item.get("difficulty", "Unknown"),prize=f"${item.get('prize', 0):,}",time_estimate=f"{item.get('duration', 0)} hours")challenges.append(challenge)# Cache results for 1 hourself.challenges_cache[cache_key] = challengesself.cache_expiry = datetime.now() + timedelta(hours=1)logger.info(f"β Fetched {len(challenges)} real challenges from MCP")return challengeslogger.warning("β Failed to fetch challenges, returning empty list")return []async def fetch_skills(self, category: str = None) -> List[Skill]:"""Fetch real skills from Topcoder MCP"""cache_key = f"skills_{category}"if (self.cache_expiry and datetime.now() < self.cache_expiry andcache_key in self.skills_cache):return self.skills_cache[cache_key]arguments = {}if category:arguments["category"] = categoryresult = await self.call_mcp_tool("query-tc-skills", arguments)if result and "content" in result:skills_data = result["content"]skills = []for item in skills_data:if isinstance(item, dict):skill = Skill(name=item.get("name", "Unknown Skill"),category=item.get("category", "General"),description=item.get("description", ""))skills.append(skill)self.skills_cache[cache_key] = skillslogger.info(f"β Fetched {len(skills)} real skills from MCP")return skillslogger.warning("β Failed to fetch skills, returning empty list")return []def extract_technologies_from_query(self, query: str) -> List[str]:"""Extract technology keywords from user query"""2 unmodified lines'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'}query_lower = query.lower()found_techs = [tech for tech in tech_keywords if tech in query_lower]return found_techsdef calculate_compatibility_score(self, challenge: Challenge, user_profile: UserProfile, query: str) -> float:"""Calculate compatibility score using real challenge data"""score = 0.0factors = []5 unmodified linesskill_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_scorefactors.append(f"Skill match: {skill_matches}/{len(challenge.technologies)} technologies")# 2. Experience level matching (30%)experience_mapping = {"beginner": {"Beginner": 1.0, "Intermediate": 0.7, "Advanced": 0.3},"intermediate": {"Beginner": 0.5, "Intermediate": 1.0, "Advanced": 0.8},"advanced": {"Beginner": 0.3, "Intermediate": 0.8, "Advanced": 1.0}}exp_score = experience_mapping.get(user_profile.experience_level.lower(), {}).get(challenge.difficulty, 0.5) * 0.3score += exp_scorefactors.append(f"Experience match: {user_profile.experience_level} β {challenge.difficulty}")# 3. Query relevance (20%)query_techs = self.extract_technologies_from_query(query)query_matches = len(set([tech.lower() for tech in query_techs]) & set(challenge_techs_lower))query_score = min(query_matches / max(len(query_techs), 1), 1.0) * 0.2 if query_techs else 0.1score += query_scorefactors.append(f"Query relevance: {query_matches} matches")# 4. Time availability (10%)time_mapping = {"2-4 hours": {"1-2 hours": 1.0, "2-4 hours": 1.0, "4+ hours": 0.7},"4-8 hours": {"2-4 hours": 0.8, "4+ hours": 1.0, "1-2 hours": 0.6},"8+ hours": {"4+ hours": 1.0, "2-4 hours": 0.7, "1-2 hours": 0.4}}time_score = 0.1 # Defaultfor user_time, challenge_map in time_mapping.items():if user_time in user_profile.time_available:time_score = challenge_map.get(challenge.time_estimate, 0.5) * 0.1breakscore += time_scorefactors.append(f"Time fit: {user_profile.time_available} vs {challenge.time_estimate}")return min(score, 1.0), factorsasync def get_personalized_recommendations(self, user_profile: UserProfile, query: str = "") -> Dict[str, Any]:"""Get personalized recommendations using real MCP data"""start_time = datetime.now()# Fetch real challenges with technology filter if possiblequery_techs = self.extract_technologies_from_query(query)challenges = await self.fetch_challenges(limit=100, technologies=query_techs if query_techs else None)if not challenges:# Fallback messagereturn {"recommendations": [],"insights": {"total_challenges": 0,"processing_time": f"{(datetime.now() - start_time).total_seconds():.3f}s","data_source": "MCP (No data available)","message": "Unable to fetch real challenge data. Please check MCP connection."}}# 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"Score: {score:.1%}. " + "; ".join(factors[:2])scored_challenges.append(challenge)# Sort by compatibility score2 unmodified lines# Take top 5 recommendationsrecommendations = scored_challenges[:5]# Get skills for gap analysisskills = await self.fetch_skills()# Processing timeprocessing_time = (datetime.now() - start_time).total_seconds()return {"recommendations": [asdict(rec) for rec in recommendations],"insights": {"total_challenges": len(challenges),"average_score": sum(c.compatibility_score for c in challenges) / len(challenges),"processing_time": f"{processing_time:.3f}s","data_source": "Real Topcoder MCP","top_score": recommendations[0].compatibility_score if recommendations else 0,"skills_available": len(skills),"technologies_detected": query_techs,"cache_status": "Fresh data" if not self.cache_expiry else "Cached data"}}# Example usage and testingasync def test_real_mcp_engine():"""Test the real MCP integration"""print("π Testing Real MCP Integration")print("=" * 50)engine = RealMCPIntelligenceEngine()# Wait for connectionawait asyncio.sleep(2)if not engine.is_connected:print("β MCP connection failed - check authentication")return# Test user profileuser_profile = UserProfile(skills=["Python", "JavaScript", "API"],experience_level="Intermediate",time_available="4-8 hours",interests=["web development", "API integration"])# Test recommendationsprint("\nπ§ Getting Real Recommendations...")recommendations = await engine.get_personalized_recommendations(user_profile,"I want to work on Python API challenges")print(f"\nπ Results:")print(f" Challenges found: {recommendations['insights']['total_challenges']}")print(f" Processing time: {recommendations['insights']['processing_time']}")print(f" Data source: {recommendations['insights']['data_source']}")for i, rec in enumerate(recommendations['recommendations'][:3], 1):print(f"\n {i}. {rec['title']}")print(f" Score: {rec['compatibility_score']:.1%}")print(f" Technologies: {', '.join(rec['technologies'][:3])}")if __name__ == "__main__":asyncio.run(test_real_mcp_engine())12345678910111214 unmodified lines2728293031321 unmodified line3435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421432 unmodified lines1461471481491501511521531541551561571581591601615 unmodified lines1671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482 unmodified lines251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465"""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, timedelta14 unmodified linescompatibility_score: float = 0.0rationale: str = ""@dataclassclass UserProfile:skills: List[str]1 unmodified linetime_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"],difficulty="Intermediate",prize="$2,500",time_estimate="3-5 hours"),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"""2 unmodified lines'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','ui/ux', 'design', 'devops', 'tensorflow', 'scikit-learn'}query_lower = query.lower()found_techs = [tech for tech in tech_keywords if tech in query_lower]return found_techsdef calculate_compatibility_score(self, challenge: Challenge, user_profile: UserProfile, query: str) -> tuple:"""Calculate compatibility score with detailed rationale"""score = 0.0factors = []5 unmodified linesskill_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 score2 unmodified lines# Take top 5 recommendationsrecommendations = scored_challenges[:5]# Processing timeprocessing_time = (datetime.now() - start_time).total_seconds()# 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],"insights": {"total_challenges": len(challenges),"average_compatibility": f"{avg_score:.1%}","processing_time": f"{processing_time:.3f}s","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."recommendations = recommendations_data["recommendations"]insights = recommendations_data["insights"]# Build the displaydisplay_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'}---""")# Individual recommendationsfor 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']}**π― Compatibility Score:** {rec['compatibility_score']:.0%} | **π° Prize:** {rec['prize']} | **β±οΈ Time:** {rec['time_estimate']}**π Description:** {rec['description']}**π οΈ Technologies:** {', '.join(rec['technologies'])}**π Why This Matches:** {rec['rationale']}**π Challenge Level:** {rec['difficulty']}---""")# Footer with next stepsdisplay_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)async def get_recommendations_async(skills_input, experience_level, time_available, interests):"""Async wrapper for getting recommendations"""# Parse skillsskills = [skill.strip() for skill in skills_input.split(",") if skill.strip()]# Create user profileuser_profile = UserProfile(skills=skills,experience_level=experience_level,time_available=time_available,interests=[interests] if interests else [])# Get recommendationsrecommendations_data = await intelligence_engine.get_personalized_recommendations(user_profile, interests)return format_recommendations_display(recommendations_data)def get_recommendations_sync(skills_input, experience_level, time_available, interests):"""Synchronous wrapper for Gradio"""return asyncio.run(get_recommendations_async(skills_input, experience_level, time_available, interests))# Create Gradio interfacedef create_interface():"""Create the Gradio interface"""with gr.Blocks(title="Topcoder Challenge Intelligence Assistant",theme=gr.themes.Soft(),css=""".gradio-container {max-width: 1200px !important;}.header-text {text-align: center;margin-bottom: 2rem;}""") as interface:# Headergr.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>""")with gr.Row():with gr.Column(scale=1):gr.Markdown("### π Your Profile")skills_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)experience_level = gr.Dropdown(label="π― Experience Level",choices=["Beginner", "Intermediate", "Advanced"],value="Intermediate",info="Your overall programming experience level")time_available = gr.Dropdown(label="β° Available Time",choices=["2-4 hours", "4-8 hours", "8+ hours"],value="4-8 hours",info="How much time can you dedicate to a challenge?")interests = 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")with gr.Column(scale=2):gr.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"])# Event handlersget_recommendations_btn.click(fn=get_recommendations_sync,inputs=[skills_input, experience_level, time_available, interests],outputs=[recommendations_output])# Footergr.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>""")return interface# Create and launch interfaceif __name__ == "__main__":# Create interfaceapp = create_interface()# Launchapp.launch(server_name="0.0.0.0",server_port=7860,show_error=True)
app.py+328-262