-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
448 lines (380 loc) · 15.5 KB
/
main.py
File metadata and controls
448 lines (380 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import os
import random
import sys
import traceback
from dotenv import load_dotenv
from datetime import datetime
from fastapi import FastAPI, HTTPException, Query,Request
import google.generativeai as genai
from datetime import datetime, timedelta
import firebase_admin
from firebase_admin import firestore
from groq import Groq
from typing import List, Dict
from daily import *
from course import *
from tech import generate_tech_trends
load_dotenv()
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ========== INITIALIZATION ==========
try:
load_dotenv()
logger.info("Starting FastAPI app initialization...")
# Initialize FastAPI
app = FastAPI()
try:
logger.info("Firebase initialized successfully")
except Exception as e:
logger.error(f"Firebase initialization failed: {str(e)}")
raise
# AI Configuration with error handling
gemini_key = os.getenv("GEMINI_API_KEY")
groq_key = os.getenv("GROQ_API_KEY")
if not gemini_key:
logger.error("GEMINI_API_KEY environment variable is missing")
raise ValueError("Gemini API key is required")
if not groq_key:
logger.error("GROQ_API_KEY environment variable is missing")
raise ValueError("Groq API key is required")
genai.configure(api_key=gemini_key)
gemini = genai.GenerativeModel('gemini-pro')
groq = Groq(api_key=groq_key)
logger.info("AI services initialized successfully")
except Exception as e:
logger.error(f"Startup failed: {str(e)}\n{traceback.format_exc()}")
sys.exit(1)
# Constants for APIs
YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
GITHUB_TOKEN = os.getenv("GITHUB_API_KEY")
# Difficulty mapping for personalization
DIFFICULTY_MAPPING = {
"Beginner": ["easy", "beginner", "starter"],
"Intermediate": ["intermediate", "medium"],
"Advanced": ["advanced", "hard", "expert"]
}
# ========== CATEGORY SERVICE ==========
class CategoryService:
# List of potential categories
CATEGORIES = [
"Web Development", "Mobile Apps", "Data Science", "Machine Learning",
"Cloud Computing", "DevOps", "Cybersecurity", "Blockchain",
"UI/UX Design", "Game Development", "IoT", "AR/VR",
"Business Analytics", "Digital Marketing", "Product Management",
"Software Architecture", "API Development", "Microservices",
"Database Management", "Serverless Computing", "Event-Driven Architecture",
"Authentication & Authorization", "Performance Optimization",
"Caching Strategies", "Observability & Logging", "Scalability & Load Balancing",
"Containerization & Orchestration", "Security & Compliance",
"Backend Frameworks", "CI/CD & Infrastructure as Code",
"FinTech & Payment Systems", "E-commerce & Transactional Systems","Python"
]
# Color palette for categories
COLOR_GRADIENTS = [
["#4285F4", "#7BAAF7"], # Blue Gradient
["#34A853", "#66BB6A"], # Green Gradient
["#FBBC05", "#FFD54F"], # Yellow Gradient
["#EA4335", "#EF5350"], # Red Gradient
["#9C27B0", "#BA68C8"], # Purple Gradient
["#673AB7", "#9575CD"], # Deep Purple Gradient
["#3F51B5", "#7986CB"], # Indigo Gradient
["#2196F3", "#64B5F6"], # Light Blue Gradient
["#009688", "#4DB6AC"], # Teal Gradient
["#4CAF50", "#81C784"], # Green Gradient
["#8BC34A", "#AED581"], # Light Green Gradient
["#CDDC39", "#DCE775"], # Lime Gradient
["#FFC107", "#FFCA28"], # Amber Gradient
["#FF9800", "#FFB74D"], # Orange Gradient
["#FF5722", "#FF8A65"], # Deep Orange Gradient
["#795548", "#A1887F"] # Brown Gradient
]
@staticmethod
async def get_categories(limit: int = 3) -> List[Dict]:
"""Get random categories with consistent colors."""
selected_indices = random.sample(range(len(CategoryService.CATEGORIES)), limit)
return [{
"name": CategoryService.CATEGORIES[i],
"color": CategoryService.COLOR_GRADIENTS[i % len(CategoryService.COLOR_GRADIENTS)], # Use modulo to prevent index error
"image": f"assets/card{random.randint(1, 4)}.jpg"
} for i in selected_indices]
@staticmethod
async def get_all_categories() -> List[Dict]:
"""Get all categories for the view all page"""
return [{
"name": category,
"gradient_colors": color,
"image": f"assets/card{random.randint(1, 4)}.jpg"
} for category, color in zip(CategoryService.CATEGORIES, CategoryService.COLOR_GRADIENTS)]
@staticmethod
async def get_more_categories(excluded_categories: List[str]) -> List[Dict]:
"""Get the remaining categories that were not initially displayed."""
# Normalize excluded categories for better matching
excluded_set = {cat.strip().lower() for cat in excluded_categories}
# Filter remaining categories
remaining_categories = [
category for category in CategoryService.CATEGORIES if category.lower() not in excluded_set
]
# Assign colors properly using modulo
return [{
"name": category,
"gradient_colors": CategoryService.COLOR_GRADIENTS[i % len(CategoryService.COLOR_GRADIENTS)],
"image": f"assets/card{random.randint(1, 4)}.jpg"
} for i, category in enumerate(remaining_categories)]
# ========== CORE SERVICES ==========
class CourseService:
@staticmethod
async def get_top_rated(self,user_id: str) -> List[Dict]:
courses_ref = db.collection("courses")
query = courses_ref.order_by("rating", direction=firestore.Query.DESCENDING).limit(3)
courses = []
async for doc in query.stream():
course = doc.to_dict()
course["id"] = doc.id
course["isFavorite"] = await self._check_favorite(user_id, doc.id)
courses.append(self._format_course(course))
return courses
@staticmethod
def _format_course(course: Dict) -> Dict:
return {
"title": course.get("title", "Untitled Course"),
"duration": f"{random.randint(3, 6)} Parts",
"rating": round(random.uniform(4.5, 5.0), 1),
"learners": f"{random.randint(1000, 3000)//100 * 100}k",
"techStack": course.get("tech_stack", ["Python", "AI"]),
"imageUrl": course.get("image_url", "assets/default_course.png")
}
@staticmethod
async def _check_favorite(user_id: str, course_id: str) -> bool:
fav_ref = db.collection("users").document(user_id).collection("favorites").document(course_id)
return (await fav_ref.get()).exists
# ========== API ENDPOINTS ==========
@app.get("/daily-challenges")
async def daily_challenges(userId: str = Query(..., description="User ID")):
"""Get personalized daily challenges """
user_ref = db.collection('users').document(userId)
daily_challenges_ref = user_ref.collection("daily_challenges").document(datetime.now().strftime("%Y-%m-%d"))
# Check if today's challenges already exist
daily_challenges_doc = daily_challenges_ref.get()
if daily_challenges_doc.exists:
daily_data = daily_challenges_doc.to_dict()
return {
"challenges": daily_data.get("challenges", []),
"date": daily_data.get("date", datetime.now().strftime("%Y-%m-%d")),
"streakCount": daily_data.get("streakCount", get_streak_count(userId)),
"completedToday": daily_data.get("completedToday", [])
}
# If no challenges exist for today, generate new ones
challenges = generate_challenges_for_user(userId)
# Store new challenges in Firestore
daily_challenges_ref.set({
"challenges": challenges,
"date": datetime.now().strftime("%Y-%m-%d"),
"streakCount": get_streak_count(userId),
"completedToday": []
})
return {
"challenges": challenges,
"date": datetime.now().strftime("%Y-%m-%d"),
"streakCount": get_streak_count(userId),
"completedToday": []
}
@app.get("/categories")
async def fetch_categories(limit: int = 3):
return await CategoryService.get_categories(limit)
@app.get("/categories/all")
async def get_all_categories():
return await CategoryService.get_all_categories()
@app.get("/categories/more")
async def get_more_categories(request: Request, excluded: List[str] = Query([])):
raw_query_params = request.query_params
logger.info(f"RAW Query Params: {raw_query_params}") # Log the raw data
if excluded is None:
excluded = []
logger.info(f"Excluded Categories Received: {excluded}") # Log parsed data
return await CategoryService.get_more_categories(excluded)
@app.post("/courses/search")
async def search_course(request: Request):
"""
Endpoint to search for an existing course or generate a new one.
Expects a JSON body with 'search_query', 'user_id', and optional 'generate_new' boolean.
"""
data = await request.json()
search_query = data.get("search_query")
user_id = data.get("user_id")
generate_new = data.get("generate_new", False)
if not search_query or not user_id:
raise HTTPException(status_code=400, detail="Both 'search_query' and 'user_id' are required.")
try:
course_summary = await search_or_generate_course(db, search_query, user_id, generate_new=generate_new)
return course_summary
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/courses/{course_id}")
async def course_details(course_id: str):
"""
Endpoint to get full details of a course by course_id.
"""
try:
course_data = await get_course_details(db, course_id)
return course_data
except Exception as e:
raise HTTPException(status_code=404, detail=str(e))
@app.post("/courses/{course_id}/progress")
async def update_progress(course_id: str, request: Request):
"""
Endpoint to update a user's progress on a given course lesson.
Expects a JSON body with 'user_id', 'lesson_id', and 'completed' status.
"""
data = await request.json()
user_id = data.get("user_id")
lesson_id = data.get("lesson_id")
completed = data.get("completed", False)
if not user_id or not lesson_id:
raise HTTPException(status_code=400, detail="Both 'user_id' and 'lesson_id' are required.")
try:
progress = await update_course_progress(db, user_id, course_id, lesson_id, completed)
return progress
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/tech-trends")
async def get_tech_trends():
cache_ref = db.collection('tech_trends_cache').document('current')
try:
cache_data = cache_ref.get().to_dict()
if cache_data and datetime.now() - cache_data['timestamp'].replace(tzinfo=None) < timedelta(hours=6):
return cache_data['data']
except Exception as e:
raise HTTPException(status_code=500, detail="Firestore fetch failed")
# Generate new data
try:
groq_client = Groq(api_key=API_KEYS["GROQ_API_KEY"])
if not groq_client:
raise ValueError("groq_client is None")
except Exception as e:
raise HTTPException(status_code=500, detail="AI model initialization failed")
try:
new_trends = await generate_tech_trends(groq_client)
except Exception as e:
raise HTTPException(status_code=500, detail="Trend generation failed")
# Add weekly trend data
for trend in new_trends:
base = trend['popularity'] - 10
trend['weeklyData'] = [base + i * 2 for i in range(7)]
# Update cache
try:
cache_ref.set({
'data': new_trends,
'timestamp': datetime.now()
})
except Exception as e:
raise HTTPException(status_code=500, detail="Failed to update Firestore cache")
return new_trends
@app.get("/debug/firebase")
async def test_firebase_auth():
try:
# 1. Get the current Firebase app
app = firebase_admin.get_app()
# 2. Get the credentials from the app
creds = app.credential
# 3. Try to get an access token (remove `await`)
access_token_info = app.credential.get_access_token()
return {
"status": "success",
"project_id": app.project_id,
"service_account_email": creds.service_account_email if hasattr(creds, 'service_account_email') else None,
"token_acquired": bool(access_token_info),
"token_expiry": str(access_token_info.expiry) if access_token_info else None
}
except Exception as e:
return {
"status": "error",
"error": str(e),
"error_type": type(e).__name__
}
@app.get("/health")
async def health_check():
logger.info("Starting health check...")
status = {
"timestamp": datetime.now().isoformat(),
"components": {},
"debug_info": {} # Add debug info
}
# Check Firebase Authentication
try:
app = firebase_admin.get_app()
project_id = app.project_id
status["components"]["firebase_auth"] = {
"status": "ok",
"project_id": project_id
}
except Exception as e:
logger.error(f"Firebase auth check failed: {str(e)}")
status["components"]["firebase_auth"] = {
"status": "error",
"error": str(e)
}
# Check Firestore Connection
try:
db.collection('test').limit(1).get()
status["components"]["firestore"] = {
"status": "ok"
}
except Exception as e:
logger.error(f"Firestore check failed: {str(e)}")
status["components"]["firestore"] = {
"status": "error",
"error": str(e)
}
# Check AI Services
try:
if os.getenv("GEMINI_API_KEY"):
gemini_key_exists = True
status["components"]["gemini"] = {
"status": "ok"
}
else:
gemini_key_exists = False
status["components"]["gemini"] = {
"status": "error",
"error": "API key not found"
}
if os.getenv("GROQ_API_KEY"):
groq_key_exists = True
status["components"]["groq"] = {
"status": "ok"
}
else:
groq_key_exists = False
status["components"]["groq"] = {
"status": "error",
"error": "API key not found"
}
except Exception as e:
logger.error(f"AI services check failed: {str(e)}")
status["components"]["ai_services"] = {
"status": "error",
"error": str(e)
}
# Collect all component statuses for debugging
all_statuses = [
comp.get("status")
for comp in status["components"].values()
]
# Add debug information
status["debug_info"] = {
"all_statuses": all_statuses,
"components_checked": list(status["components"].keys()),
"has_error": "error" in all_statuses
}
# Set overall status
status["status"] = "error" if "error" in all_statuses else "ok"
# Log the final status
logger.info(f"Health check complete. Status: {status['status']}")
logger.info(f"Component statuses: {all_statuses}")
return status
# ========== STARTUP ==========
@app.get("/")
async def root():
return {"message": "Hello from Railway!"}