diff --git a/ai_solution.py b/ai_solution.py new file mode 100644 index 00000000000..33f6c757ea0 --- /dev/null +++ b/ai_solution.py @@ -0,0 +1,8 @@ +# Solution + +```json +{ + "solution_code": "import requests\nimport hashlib\nfrom datetime import datetime\nfrom typing import List, Dict, Optional\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nALGORA_API_URL = \"https://algora.io/api/bounties?status=open&limit=50\"\n\n\ndef fetch_algora_bounties() -> List[Dict]:\n \"\"\"\n Fetch open bounties from Algora API.\n \n Returns:\n List of bounty dictionaries from Algora\n \"\"\"\n try:\n response = requests.get(ALGORA_API_URL, timeout=30)\n response.raise_for_status()\n data = response.json()\n \n # Algora API returns bounties in different possible structures\n # Handle both direct list and nested data structure\n if isinstance(data, list):\n bounties = data\n elif isinstance(data, dict) and 'bounties' in data:\n bounties = data['bounties']\n elif isinstance(data, dict) and 'data' in data:\n bounties = data['data']\n else:\n logger.warning(f\"Unexpected Algora API response structure: {type(data)}\")\n bounties = []\n \n logger.info(f\"Fetched {len(bounties)} bounties from Algora\")\n return bounties\n except requests.exceptions.RequestException as e:\n logger.error(f\"Failed to fetch Algora bounties: {e}\")\n return []\n except Exception as e:\n logger.error(f\"Error processing Algora response: {e}\")\n return []\n\n\ndef parse_algora_bounty(bounty: Dict) -> Optional[Dict]:\n \"\"\"\n Parse an Algora bounty into runtime_jobs format.\n \n Args:\n bounty: Raw bounty dict from Algora API\n \n Returns:\n Parsed job dict ready for insertion, or None if invalid\n \"\"\"\n try:\n # Extract URL - try multiple possible fields\n url = bounty.get('url') or bounty.get('html_url') or bounty.get('link')\n if not url:\n # Construct URL from bounty ID if available\n bounty_id = bounty.get('id')\n if bounty_id:\n url = f\"https://algora.io/bounties/{bounty_id}\"\n else:\n logger.warning(f\"No URL found for bounty: {bounty}\")\n return None\n \n # Generate idempotent task_id from URL using SHA-1\n task_id = hashlib.sha1(url.encode('utf-8')).hexdigest()\n \n # Extract title\n title = bounty.get('title') or bounty.get('name') or 'Algora Bounty'\n \n # Extract reward in USD - be strict, only accept real numeric values\n reward_usd = None\n reward_fields = ['reward_usd', 'reward', 'amount', 'prize', 'reward_in_usd']\n \n for field in reward_fields:\n if field in bounty:\n try:\n value = bounty[field]\n if isinstance(value, (int, float)):\n reward_usd = float(value)\n break\n elif isinstance(value, str):\n # Try to parse numeric string\n cleaned = value.replace('$', '').replace(',', '').strip()\n reward_usd = float(cleaned)\n break\n except (ValueError, TypeError):\n continue\n \n # Extract tech stack / technologies\n tech_stack = []\n tech_fields = ['tech_stack', 'technologies', 'tags', 'skills', 'languages']\n \n for field in tech_fields:\n if field in bounty:\n value = bounty[field]\n if isinstance(value, list):\n tech_stack.extend([str(t) for t in value if t])\n elif isinstance(value, str) and value:\n tech_stack.append(value)\n \n # Also check for language/framework in bounty object\n if 'language' in bounty and bounty['language']:\n tech_stack.append(str(bounty['language']))\n if 'framework' in bounty and bounty['framework']:\n tech_stack.append(str(bounty['framework']))\n \n # Remove duplicates and limit length\n tech_stack = list(set(tech_stack))[:10]\n \n # Build description\n description_parts = [f\"Algora Bounty: {title}\"]\n if reward_usd:\n description_parts.append(f\"Reward: ${reward_usd:.2f} USD\")\n if tech_stack:\n description_parts.append(f\"Tech: {', '.join(tech_stack)}\")\n if bounty.get('description'):\n description_parts.append(bounty['description'][:500])\n \n description = \"\\n\\n\".join(description_parts)\n \n return {\n 'task_id': task_id,\n 'source': 'algora',\n 'title': title[:500], # Limit title length\n 'description': description[:2000], # Limit description\n 'url': url,\n 'reward_usd': reward_usd,\n 'tech_stack': tech_stack,\n 'discovered_at': datetime.utcnow().isoformat(),\n 'status': 'open'\n }\n \n except Exception as e:\n logger.error(f\"Error parsing Algora bounty: {e}\")\n return None\n\n\ndef insert_runtime_job(job: Dict, db_connection) -> bool:\n \"\"\"\n Insert a job into runtime_jobs table with idempotent upsert.\n \n Args:\n job: Parsed job dictionary\n db_connection: Database connection object\n \n Returns:\n True if inserted/updated, False if error\n \"\"\"\n try:\n # This is a placeholder - actual implementation depends on your DB setup\n # Using task_id as primary key ensures idempotency\n \n query = \"\"\"\n INSERT INTO runtime_jobs (\n task_id, source, title, description, url, \n reward_usd, tech_stack, discovered_at, status\n ) VALUES (\n %(task_id)s, %(source)s, %(title)s, %(description)s, %(url)s,\n %(reward_usd)s, %(tech_stack)s, %(discovered_at)s, %(status)s\n )\n ON CONFLICT (task_id) DO UPDATE SET\n title = EXCLUDED.title,\n description = EXCLUDED.description,\n reward_usd = EXCLUDED.reward_usd,\n tech_stack = EXCLUDED.tech_stack,\n discovered_at = EXCLUDED.discovered_at,\n status = EXCLUDED.status\n \"\"\"\n \n cursor = db_connection.cursor()\n cursor.execute(query, job)\n db_connection.commit()\n cursor.close()\n \n logger.info(f\"Inserted/updated job {job['task_id']}: {job['title']}\")\n return True\n \n except Exception as e:\n logger.error(f\"Failed to insert job {job.get('task_id')}: {e}\")\n return False\n\n\ndef sync_algora_bounties(db_connection) -> int:\n \"\"\"\n Main function to sync Algora bounties to runtime_jobs.\n \n Args:\n db_connection: Database connection\n \n Returns:\n Number of jobs successfully synced\n \"\"\"\n logger.info(\"Starting Algora bounty sync...\")\n \n bounties = fetch_algora_bounties()\n if not bounties:\n logger.warning(\"No bounties fetched from Algora\")\n return 0\n \n success_count = 0\n \n for bounty in bounties:\n parsed = parse_algora_bounty(bounty)\n if parsed:\n if insert_runtime_job(parsed, db_connection):\n success_count += 1\n \n logger.info(f\"Algora sync complete: {success_count}/{len(bounties)} jobs synced\")\n return success_count\n\n\nif __name__ == \"__main__\":\n # Example usage / testing\n logging.basicConfig(level=logging.INFO)\n \n # Fetch and print sample data\n bounties = fetch_algora_bounties()\n print(f\"\\nFetched {len(bounties)} bounties from Algora\\n\")\n \n if bounties:\n print(\"Sample bounty (first one):\")\n print(\"=\" * 60)\n import json\n print(json.dumps(bounties[0], indent=2))\n print(\"=\" * 60)\n \n print(\"\\nParsed format:\")\n parsed = parse_algora_bounty(bounties[0])\n if parsed:\n print(json.dumps(parsed, indent=2, default=str))\n", + "file_hints": [ + "runtime-opportunity-scout/algora_integration.py", + "runtime-opportunity-scout/src/algora_scout.py \ No newline at end of file