Upload app.py
Browse files34 unmodified lines35363738383940411 unmodified line4344454646474848495056 unmodified lines1071081091111101111131121131144 unmodified lines1191201211241221231261271241251301261271281293 unmodified lines13313413514013613713813911 unmodified lines1511521531581541551561571 unmodified line1591601611661621631641651 unmodified line1671681691741701711721771731741791751761811821771781851791801811821831841851921861871881893 unmodified lines1931941952021961971981991 unmodified line2012022032102042052062073 unmodified lines2112122132202142152162232172182252192202272282292212222232332342242252262272282292402412302312322332 unmodified lines2362372382502512392402412422 unmodified lines2452462472602482492622632502512652522532543 unmodified lines2582592602752612772782622632642812652662672682692872702712722734 unmodified lines2782792802982993003012812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113043053063123133143153163173183193203213223233243253263273283293303313323333343353363373383093103393403123133413423433443183193203453463473483492 unmodified lines3523533543293553563323333573583593603 unmodified lines3643653663433673683453463473483493503513523533543553563573583593603613623693703643653713723683693733743723733753753763773773793783793803833843813823863833843851 unmodified line3873883893943953903913923993933943954 unmodified lines4004014024104034124134044054061 unmodified line40840941042141141241341442641542842941643141741841942043643742142242342444144242542644442744642842944843043143245245343343443543643743846043946246344044144244344444547047144644744810 unmodified lines4594604614884894624634643 unmodified lines4684694704994715014724735034745054754764774 unmodified lines4824834845164854865194875214884895234904914924 unmodified lines4974984995345005015025035045405055425065075445085095105485115125132 unmodified lines516517518557558559560519520521522523524525526527528563564565566529530531532533534535536537538539540541542543544545546547572548549550576577551552553554555556557584585558587588559590591560593594561562597563564565601566567568389 unmodified lines9589599609979989991000100110021003100410051006100710081009101010111012101310141015101610171018101996196296396496596696710211022968969970971972973102910301031974975976977978979980981982983984985986987103398898910369909919929939949959969979989991000100110021003100442 unmodified lines10471048104910851086108710881050105110521053105410551056105710581059106010611062142 unmodified lines12051206120712081209121012111239124012121213121412151216124412171246121812191248122012211222125212531223122412551225122612271259126012281229126212301231123212661233126812341235127012361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279127712781279128012811282128312841285128012811282128312871288128912901291129212931294129512961284128512861287128812891299129012911292129312941295129612971298129913001301130213031304130534 unmodified lines
class 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 line self.is_connected = False
self.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 lines registrants=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 lines except json.JSONDecodeError:
pass
return None
async def initialize_connection(self) -> bool:
"""Initialize MCP connection with enhanced error handling"""
if self.is_connected:
return True
headers = {
"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 line json=init_request,
headers=headers
)
if response.status_code == 200:
response_headers = dict(response.headers)
if 'mcp-session-id' in response_headers:1 unmodified line self.is_connected = True
print(f"β
Real MCP connection established: {self.session_id[:8]}...")
return True
except Exception as e:
print(f"β οΈ MCP connection failed, using enhanced fallback: {e}")
return False
async 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 None
headers = {
"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 line json=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 lines json_data = response.json()
if "result" in json_data:
return json_data["result"]
except Exception:
pass
return None
def convert_topcoder_challenge(self, tc_data: Dict) -> Challenge:
"""Convert real Topcoder challenge data with enhanced parsing"""
# Extract real fields from Topcoder data structure
challenge_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 array
technologies = []
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 field
if 'technologies' in tc_data:
tech_list = tc_data['technologies']
if isinstance(tech_list, list):2 unmodified lines technologies.append(tech['name'])
elif isinstance(tech, str):
technologies.append(tech)
# Calculate total prize from prizeSets
total_prize = 0
prize_sets = tc_data.get('prizeSets', [])
for prize_set in prize_sets:2 unmodified lines 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"
# Map challenge type to difficulty
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 and registrants
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 lines time_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"""
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_techs
async 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 []
result = await self.call_tool("query-tc-challenges", {"limit": limit})
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_min
if prize_max is not None:
mcp_query["totalPrizesTo"] = prize_max
if challenge_type:
mcp_query["type"] = challenge_type
if track:
mcp_query["track"] = track
if skill_keywords:
mcp_query["tags"] = skill_keywords
if 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 []
# Extract challenge data using the fixed parsing method
challenge_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 parsing
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 lines parsed_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 objects
challenges = []
for item in challenge_data_list:
if isinstance(item, dict):3 unmodified lines except Exception as e:
print(f"Error converting challenge: {e}")
continue
return challenges
def 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_techs
def calculate_advanced_compatibility_score(self, challenge: Challenge, user_profile: UserProfile, query: str) -> tuple:
"""ENHANCED compatibility scoring algorithm with detailed analysis"""
score = 0.0
factors = []
# Convert to lowercase for matching
user_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 score
exact_match_score = (skill_matches / len(challenge.technologies)) * 30
# Coverage bonus for multiple matches
coverage_bonus = min(skill_matches * 10, 10)
skill_score = exact_match_score + coverage_bonus
else:
skill_score = 30 # Default for general challenges
skill_score = 30
score += skill_score
if 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 line factors.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 lines else:
level_score = 5
factors.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 line query_score = min(query_matches / len(query_techs), 1.0) * 20
else:
query_score = 10
if query_matches > 0:
factors.append(f"Directly matches your interest in {', '.join(query_techs[:2])}")
else:
query_score = 10
score += query_score
# 4. Market Attractiveness (10% weight)
try:
# Extract numeric value from prize string
prize_numeric = 0
if challenge.prize.startswith('$'):
prize_str = challenge.prize[1:].replace(',', '')
prize_numeric = int(prize_str) if prize_str.isdigit() else 0
prize_score = min(prize_numeric / 1000 * 2, 8) # Max 8 points
prize_score = min(prize_numeric / 1000 * 2, 8)
competition_bonus = 2 if 20 <= challenge.registrants <= 50 else 0
market_score = prize_score + competition_bonus
except:
market_score = 5 # Default market score
market_score = 5
score += market_score
return min(score, 100.0), factors
def get_user_insights(self, user_profile: UserProfile) -> Dict:
"""Generate comprehensive user insights with market intelligence"""
skills = user_profile.skills
level = user_profile.experience_level
time_available = user_profile.time_available
# Analyze skill categories
frontend_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 strengths
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))
# Determine profile type with enhanced categories
if blockchain_count >= 2:
profile_type = "Blockchain Developer"
elif frontend_count >= 2 and backend_count >= 1:10 unmodified lines profile_type = "DevOps Engineer"
else:
profile_type = "Versatile Developer"
# Generate comprehensive insights
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 insights
def _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 lines suggestions.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 trend
return "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_bonus
if total >= 90:
return f"{total}% - Outstanding success potential"
elif total >= 80:2 unmodified lines return 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"""
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}")
# Try to get real challenges first
real_challenges = await self.fetch_real_challenges(limit=50)
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_challenges
data_source = "π₯ REAL Topcoder MCP Server (4,596+ challenges)"
print(f"π Using {len(challenges)} REAL Topcoder challenges!")
else:
# Fallback to enhanced mock data
challenges = self.mock_challenges
data_source = "β¨ Enhanced Intelligence Engine (Premium Dataset)"
print(f"β‘ Using {len(challenges)} premium challenges with advanced algorithms")
# Apply ADVANCED scoring algorithm
scored_challenges = []
for challenge in challenges:
score, factors = self.calculate_advanced_compatibility_score(challenge, user_profile, query)
challenge.compatibility_score = score
challenge.rationale = f"Match: {score:.0f}%. " + ". ".join(factors[:2]) + "."
scored_challenges.append(challenge)
# Sort by advanced compatibility score
scored_challenges.sort(key=lambda x: x.compatibility_score, reverse=True)
# Return top recommendations
recommendations = scored_challenges[:5]
# Processing time
processing_time = (datetime.now() - start_time).total_seconds()
# Generate comprehensive insights
query_techs = self.extract_technologies_from_query(query)
avg_score = sum(c.compatibility_score for c in challenges) / len(challenges) if challenges else 0
print(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 validation
if 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 skills
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()]
# Create comprehensive user profile
user_profile = UserProfile(
skills=skills,
experience_level=experience_level,
time_available=time_available,
interests=[interests] if interests else []
)
# Get ULTIMATE AI recommendations
recommendations_data = await intelligence_engine.get_personalized_recommendations(user_profile, interests)
# Pass all new filter params to get_personalized_recommendations
recommendations_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 styling
if recommendations:
# Success header with data source info42 unmodified lines print(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 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 lines with 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:**")
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...",
info="Enter your skills separated by commas - the more specific, the better!",
lines=3,
value="Python, JavaScript, React" # Default for quick testing
value="Python, JavaScript, React"
)
experience_level = gr.Dropdown(
choices=["Beginner", "Intermediate", "Advanced"],
label="π Experience Level",
value="Intermediate",
info="Your overall development and competitive coding experience"
value="Intermediate"
)
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?"
value="4-8 hours"
)
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
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"
)
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!
""")
# ...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
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],
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