-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
487 lines (408 loc) · 17.7 KB
/
app.py
File metadata and controls
487 lines (408 loc) · 17.7 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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
from dotenv import load_dotenv
import os
from groq import Groq
import json
import re
import sys
from google.oauth2 import id_token
from google.auth.transport import requests as google_requests
# Set UTF-8 encoding for console output on Windows
if sys.platform == 'win32':
import codecs
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')
# Load environment variables
load_dotenv()
# Initialize Flask app
app = Flask(__name__, static_folder='dist', static_url_path='')
CORS(app)
app.secret_key = os.getenv("SECRET_KEY", "dev-secret-key")
# Initialize Groq client
groq_api_key = os.getenv("GROQ_API_KEY")
print(f"DEBUG: GROQ_API_KEY found: {bool(groq_api_key)}")
print(f"DEBUG: API Key starts with: {groq_api_key[:10] if groq_api_key else 'None'}...")
if groq_api_key and groq_api_key != "your_groq_api_key_here":
try:
client = Groq(api_key=groq_api_key)
print("✅ Groq AI client initialized successfully!")
except Exception as e:
print(f"❌ Groq initialization failed: {e}")
client = None
else:
print("⚠️ Groq API key not configured. AI features will be disabled.")
print(f" Key value: {groq_api_key}")
client = None
def parse_json_safely(text):
"""Parse JSON with multiple fallback strategies"""
# Strategy 1: Direct parse
try:
return json.loads(text)
except:
pass
# Strategy 2: Extract JSON from markdown code blocks
json_match = re.search(r'```(?:json)?\s*(\[.*?\])\s*```', text, re.DOTALL)
if json_match:
try:
return json.loads(json_match.group(1))
except:
pass
# Strategy 3: Find array pattern
array_match = re.search(r'\[\s*\{.*?\}\s*\]', text, re.DOTALL)
if array_match:
try:
json_str = array_match.group(0)
# Fix common JSON issues
json_str = re.sub(r',(\s*[}\]])', r'\1', json_str) # Remove trailing commas
return json.loads(json_str)
except:
pass
# Strategy 4: Return None if all fail
return None
def create_fallback_roadmap(goal, level, language):
"""Create a basic fallback roadmap when AI generation fails"""
return [
{
"level": "Foundation",
"nodes": [
{
"title": f"{language} Basics",
"description": f"Master the fundamentals of {language} programming",
"progress": 0,
"subTopics": [
{"title": "Syntax and Basic Concepts", "desc": "Variables, data types, operators", "completed": False},
{"title": "Control Structures", "desc": "If statements, loops, conditionals", "completed": False},
{"title": "Functions and Methods", "desc": "Creating reusable code blocks", "completed": False},
{"title": "Data Structures", "desc": "Arrays, lists, objects", "completed": False},
{"title": "Error Handling", "desc": "Try-catch, debugging basics", "completed": False}
]
},
{
"title": "Development Environment",
"description": "Set up your development tools and workflow",
"progress": 0,
"subTopics": [
{"title": "IDE Setup", "desc": "Install and configure your code editor", "completed": False},
{"title": "Version Control", "desc": "Git basics and GitHub", "completed": False},
{"title": "Command Line", "desc": "Terminal/shell basics", "completed": False},
{"title": "Package Managers", "desc": "npm, pip, or similar tools", "completed": False}
]
}
]
},
{
"level": "Intermediate",
"nodes": [
{
"title": f"Advanced {language}",
"description": "Deep dive into advanced programming concepts",
"progress": 0,
"subTopics": [
{"title": "Object-Oriented Programming", "desc": "Classes, inheritance, polymorphism", "completed": False},
{"title": "Async Programming", "desc": "Promises, async/await, callbacks", "completed": False},
{"title": "Design Patterns", "desc": "Common software design patterns", "completed": False},
{"title": "Testing", "desc": "Unit tests, integration tests", "completed": False},
{"title": "Performance Optimization", "desc": "Code efficiency and best practices", "completed": False}
]
},
{
"title": f"{goal} Fundamentals",
"description": f"Core concepts for {goal}",
"progress": 0,
"subTopics": [
{"title": "Architecture Patterns", "desc": "System design fundamentals", "completed": False},
{"title": "APIs and Integration", "desc": "RESTful APIs, HTTP methods", "completed": False},
{"title": "Databases", "desc": "SQL and NoSQL basics", "completed": False},
{"title": "Security Basics", "desc": "Authentication, authorization", "completed": False}
]
}
]
},
{
"level": "Advanced",
"nodes": [
{
"title": "Professional Development",
"description": "Skills needed for professional work",
"progress": 0,
"subTopics": [
{"title": "Code Review", "desc": "Best practices for reviewing code", "completed": False},
{"title": "CI/CD", "desc": "Continuous integration and deployment", "completed": False},
{"title": "Monitoring & Logging", "desc": "Application observability", "completed": False},
{"title": "Documentation", "desc": "Writing clear technical docs", "completed": False},
{"title": "Team Collaboration", "desc": "Agile, scrum, code collaboration", "completed": False}
]
},
{
"title": "Specialization",
"description": f"Specialize in {goal} technologies",
"progress": 0,
"subTopics": [
{"title": "Framework Mastery", "desc": "Deep knowledge of key frameworks", "completed": False},
{"title": "Performance Tuning", "desc": "Optimization at scale", "completed": False},
{"title": "Cloud Deployment", "desc": "AWS, Azure, or GCP", "completed": False},
{"title": "Microservices", "desc": "Distributed systems architecture", "completed": False}
]
}
]
}
]
@app.route("/api/auth/google", methods=["POST"])
def google_auth():
"""Verify Google OAuth token and return user information"""
try:
data = request.get_json()
token = data.get('credential')
if not token:
return jsonify({"error": "No credential provided"}), 400
# Get Google Client ID from environment
google_client_id = os.getenv("GOOGLE_CLIENT_ID")
if not google_client_id:
return jsonify({"error": "Google Client ID not configured"}), 500
# Verify the token with Google
idinfo = id_token.verify_oauth2_token(
token,
google_requests.Request(),
google_client_id
)
# Extract user information
user_data = {
"email": idinfo.get("email"),
"name": idinfo.get("name"),
"picture": idinfo.get("picture"),
"email_verified": idinfo.get("email_verified")
}
return jsonify({
"success": True,
"user": user_data
}), 200
except ValueError as e:
# Invalid token
print(f"Token verification failed: {e}")
return jsonify({"error": "Invalid token"}), 401
except Exception as e:
print(f"Authentication error: {e}")
return jsonify({"error": "Authentication failed"}), 500
@app.route("/generate-roadmap", methods=["POST"])
def generate_roadmap():
"""Generate a comprehensive learning roadmap using AI"""
if not client:
# Return fallback roadmap if AI is not available
data = request.get_json()
goal = data.get("goal", "Developer")
level = data.get("level", "beginner")
language = data.get("language", "Python")
fallback_roadmap = create_fallback_roadmap(goal, level, language)
return jsonify({
"status": "success",
"roadmap": f"Basic {goal} Learning Roadmap for {level} level using {language}",
"roadmap_json": fallback_roadmap,
"message": "⚠️ Using fallback roadmap. Add Groq API key for AI-generated roadmaps."
})
try:
data = request.get_json()
goal = data.get("goal")
level = data.get("level")
language = data.get("language")
description = data.get("description", "")
print(f"\n🎯 Generating roadmap: {goal} | {level} | {language}")
if not all([goal, level, language]):
return jsonify({"status": "error", "message": "Missing required fields"}), 400
# Generate structured JSON roadmap
json_prompt = f"""Create a learning roadmap JSON for a {level} developer who wants to become a {goal} using {language}.
Return ONLY valid JSON in this EXACT format (no markdown, no extra text):
[
{{
"level": "Foundation",
"nodes": [
{{
"title": "Topic Name",
"description": "Brief description",
"progress": 0,
"subTopics": [
{{"title": "Subtopic 1", "desc": "Description", "completed": false}},
{{"title": "Subtopic 2", "desc": "Description", "completed": false}}
]
}}
]
}}
]
Create 3-4 levels (Foundation, Intermediate, Advanced, Expert).
Each level should have 2-3 nodes.
Each node should have 5-7 subtopics.
Focus on {goal} skills using {language}.
Make it practical and career-focused."""
print("📋 Requesting AI roadmap generation...")
response = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[{"role": "user", "content": json_prompt}],
temperature=0.1,
max_tokens=3000
)
raw_output = response.choices[0].message.content.strip()
print(f"📦 Received response ({len(raw_output)} chars)")
# Parse the JSON response
roadmap_json = parse_json_safely(raw_output)
if not roadmap_json or not isinstance(roadmap_json, list):
print("⚠️ AI parsing failed, using fallback")
roadmap_json = create_fallback_roadmap(goal, level, language)
else:
print(f"✅ Successfully parsed {len(roadmap_json)} levels")
# Generate descriptive text
text_prompt = f"""Create a motivational and informative overview for becoming a {goal} using {language} at {level} level.
Include:
1. Brief introduction (2-3 sentences)
2. Key skills you'll develop (3-4 bullet points)
3. Career opportunities (2-3 sentences)
4. Tips for success (2-3 bullet points)
Keep it concise and encouraging."""
try:
text_response = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[{"role": "user", "content": text_prompt}],
temperature=0.5,
max_tokens=500
)
roadmap_text = text_response.choices[0].message.content.strip()
except:
roadmap_text = f"Your personalized {goal} learning roadmap using {language}. Follow the structured path to achieve your career goals!"
print("✅ Roadmap generation completed!\n")
return jsonify({
"status": "success",
"roadmap": roadmap_text,
"roadmap_json": roadmap_json,
"message": f"Generated {len(roadmap_json)} level roadmap"
})
except Exception as e:
print(f"❌ Error: {e}")
# Return fallback on any error
data = request.get_json()
fallback_roadmap = create_fallback_roadmap(
data.get("goal", "Developer"),
data.get("level", "beginner"),
data.get("language", "Python")
)
return jsonify({
"status": "success",
"roadmap": "Fallback roadmap generated",
"roadmap_json": fallback_roadmap,
"message": f"Error occurred: {str(e)}. Using fallback roadmap."
})
@app.route("/explain-topic")
def explain_topic():
"""Get detailed explanation of a topic"""
if not client:
return jsonify({
"status": "error",
"message": "⚠️ Groq API key not configured. Please add your API key to the .env file and restart the server."
}), 500
topic = request.args.get("topic", "")
technology = request.args.get("technology", "")
if not topic:
return jsonify({"status": "error", "message": "Missing topic"}), 400
context = f" in the context of {technology}" if technology else ""
prompt = f"""Provide a comprehensive explanation of '{topic}'{context} for software developers.
Structure your response EXACTLY with these section headers (use ## for headers):
## Overview
Write 2-3 paragraphs explaining what this is, why it matters, and where it's used in modern development.
## Core Concepts
List key principles as bullet points (use - or •):
- Concept 1: Clear explanation
- Concept 2: Clear explanation
- Concept 3: Clear explanation
(Add more as needed)
## Technical Implementation
Write detailed paragraphs explaining how to implement or use this in real projects. Include technical specifics.
## Practical Examples
List real-world examples as bullet points:
- Example 1: Specific use case
- Example 2: Specific use case
- Example 3: Specific use case
(Add more as needed)
## Best Practices
List industry standards as bullet points:
- Best practice 1: Why it's important
- Best practice 2: Why it's important
- Best practice 3: Why it's important
(Add more as needed)
## Common Pitfalls
Write 1-2 paragraphs about mistakes to avoid and how to prevent them.
## Career Relevance
Write 1 paragraph explaining why this matters professionally and where it's used in industry.
## Next Steps
List what to learn next as bullet points:
- Next topic 1
- Next topic 2
- Next topic 3
Make it informative, well-structured, and actionable. Use clear formatting."""
try:
print(f"🔍 Explaining: {topic}{context}")
response = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[{"role": "user", "content": prompt}],
temperature=0.4,
max_tokens=2000
)
explanation = response.choices[0].message.content.strip()
print(f"✅ Generated explanation ({len(explanation)} chars)")
return jsonify({"status": "success", "explanation": explanation})
except Exception as e:
import traceback
error_msg = str(e)
print(f"❌ Explanation error: {error_msg}")
print(f"❌ Full traceback:")
traceback.print_exc()
if "api" in error_msg.lower() or "key" in error_msg.lower() or "auth" in error_msg.lower():
return jsonify({
"status": "error",
"message": "⚠️ API authentication failed. Please check your Groq API key."
}), 500
return jsonify({
"status": "error",
"message": f"Failed to generate explanation: {error_msg}"
}), 500
@app.route("/health")
def health():
"""Health check endpoint"""
groq_status = "✅ Connected" if client else "⚠️ Not configured"
return jsonify({
"status": "healthy",
"message": "DevOdos Backend API",
"groq_ai": groq_status,
"database": "Not required (standalone mode)"
})
# Serve React app
@app.route('/')
def serve_frontend():
"""Serve the React frontend"""
try:
return send_from_directory('dist', 'index.html')
except:
return jsonify({
"message": "Frontend not built",
"instructions": "Run 'npm run build' to build the frontend"
}), 404
@app.route('/<path:path>')
def serve_static(path):
"""Serve static files"""
try:
return send_from_directory('dist', path)
except:
# For client-side routing, serve index.html
try:
return send_from_directory('dist', 'index.html')
except:
return jsonify({"error": "File not found"}), 404
if __name__ == "__main__":
port = int(os.getenv("PORT", 5001))
debug_mode = os.getenv("FLASK_ENV") == "development"
print("\n" + "="*60)
print("🚀 DevOdos Backend Server")
print("="*60)
print(f"Backend API: http://localhost:{port}")
print(f"Groq AI: {'✅ Ready' if client else '⚠️ Add API key to .env'}")
print(f"Database: Not required (standalone)")
print(f"Environment: {os.getenv('FLASK_ENV', 'production')}")
print("="*60 + "\n")
app.run(host="0.0.0.0", port=port, debug=debug_mode)