amitbhatt6075 commited on
Commit
628b5b4
Β·
1 Parent(s): 87fb30d

feat: Add Background Worker for Async AI Jobs

Browse files
Files changed (1) hide show
  1. worker.py +0 -141
worker.py DELETED
@@ -1,141 +0,0 @@
1
- import time
2
- import os
3
- import json
4
- import httpx
5
- import datetime
6
- from supabase import create_client
7
- from dotenv import load_dotenv
8
-
9
- # Environment Load
10
- load_dotenv()
11
-
12
- # Setup Database
13
- url = os.environ.get("SUPABASE_URL")
14
- key = os.environ.get("SUPABASE_SERVICE_KEY")
15
- if not url or not key:
16
- print("❌ CRITICAL: Supabase Creds missing in .env")
17
- exit(1)
18
-
19
- supabase = create_client(url, key)
20
-
21
- # ========================================================
22
- # 🧠 AI LOGIC HANDLER
23
- # ========================================================
24
- def perform_ai_task(job_type, inputs):
25
- """
26
- Dispatcher: Inputs leke asli logic chalata hai.
27
- Heavy processing ya LLM calls yahan honge.
28
- """
29
- print(f" πŸ€– Processing logic for: {job_type}")
30
-
31
- # --- TASK 1: BRAND STRATEGY ---
32
- if job_type == 'generate_campaign_strategy':
33
- time.sleep(5) # Simulate AI thinking
34
- return {
35
- "title": f"Viral Campaign for {inputs.get('brand_name')}",
36
- "description": f"Focusing on {inputs.get('target_audience')} with high-energy content.",
37
- "budget": inputs.get('budget_range'),
38
- "goalKpi": inputs.get('campaign_goal'),
39
- "contentGuidelines": ["Use trending audio", "Keep duration under 30s", "Show product in first 3s"],
40
- "suggestedInfluencers": inputs.get('influencers_context', [])[:3]
41
- }
42
-
43
- # --- TASK 2: INFLUENCER RECOMMENDATIONS (NEW) ---
44
- elif job_type == 'generate_recommendations':
45
- print(f" πŸ” AI Matching campaigns for User: {inputs.get('user_id')}...")
46
- time.sleep(4) # Simulate DB scanning + Matching
47
-
48
- # MOCK DATA: Isse real database se replace kar sakte ho baad mein
49
- # Abhi ke liye, AI ye campaigns 'dhoond' kar laya hai:
50
- return [
51
- {
52
- "id": "mock-ai-1",
53
- "title": "Nike Summer Fitness",
54
- "description": "High energy fitness campaign for Gen-Z runners.",
55
- "budget": 5000,
56
- "brand": {"fullName": "Nike Official"}
57
- },
58
- {
59
- "id": "mock-ai-2",
60
- "title": "Tech Unboxing 2025",
61
- "description": "Reviewing the latest AI gadgets.",
62
- "budget": 1200,
63
- "brand": {"fullName": "Sony Tech"}
64
- },
65
- {
66
- "id": "mock-ai-3",
67
- "title": "Sustainable Fashion",
68
- "description": "Eco-friendly clothing line launch.",
69
- "budget": 3000,
70
- "brand": {"fullName": "H&M Conscious"}
71
- }
72
- ]
73
-
74
- # --- UNKNOWN ---
75
- else:
76
- raise ValueError(f"Unknown job type: {job_type}")
77
-
78
-
79
- # ========================================================
80
- # πŸ‘· MAIN WORKER LOOP
81
- # ========================================================
82
- def worker_loop():
83
- print("πŸ‘· AI Worker online. Polling 'system_jobs' for PENDING tasks...")
84
-
85
- while True:
86
- try:
87
- # 1. Fetch PENDING Jobs (Limit 1 to avoid overlap)
88
- res = supabase.table('system_jobs')\
89
- .select('*')\
90
- .eq('status', 'PENDING')\
91
- .order('created_at', desc=False)\
92
- .limit(1)\
93
- .execute()
94
-
95
- jobs = res.data
96
-
97
- # Agar koi kaam nahi, to 3 second so jao
98
- if not jobs:
99
- time.sleep(3)
100
- continue
101
-
102
- current_job = jobs[0]
103
- # Safety: Supabase v2 might return different structures, safe get
104
- job_id = current_job['id']
105
- print(f"πŸ”„ Picked Job [{job_id}] - {current_job.get('job_type')}")
106
-
107
- # 2. Mark as PROCESSING (Lock the job)
108
- supabase.table('system_jobs').update({
109
- 'status': 'PROCESSING',
110
- 'started_at': datetime.datetime.utcnow().isoformat()
111
- }).eq('id', job_id).execute()
112
-
113
- # 3. DO THE WORK (Call Dispatcher)
114
- try:
115
- result = perform_ai_task(current_job.get('job_type'), current_job.get('input_params'))
116
-
117
- # 4. Success! Save Result
118
- supabase.table('system_jobs').update({
119
- 'status': 'COMPLETED',
120
- 'result_data': result,
121
- 'completed_at': datetime.datetime.utcnow().isoformat()
122
- }).eq('id', job_id).execute()
123
-
124
- print(f"βœ… Job [{job_id}] Completed Successfully.")
125
-
126
- except Exception as task_error:
127
- # Job Logic mein error (Code phat gaya)
128
- print(f"❌ Job [{job_id}] Logic Failed: {task_error}")
129
- supabase.table('system_jobs').update({
130
- 'status': 'FAILED',
131
- 'error_message': str(task_error),
132
- 'completed_at': datetime.datetime.utcnow().isoformat()
133
- }).eq('id', job_id).execute()
134
-
135
- except Exception as conn_error:
136
- # Database/Network Error
137
- print(f"⚠️ Worker Loop Warning: {conn_error}")
138
- time.sleep(5) # Thoda lamba so jao agar net gaya hai
139
-
140
- if __name__ == "__main__":
141
- worker_loop()