andevs commited on
Commit
6bac09b
·
verified ·
1 Parent(s): b73c039

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -291
app.py CHANGED
@@ -1,5 +1,5 @@
1
  """
2
- StudyFlow AI Backend - Complete Working Version for Hugging Face Spaces
3
  """
4
  import os
5
  import json
@@ -7,14 +7,12 @@ import sqlite3
7
  import hashlib
8
  import tempfile
9
  from datetime import datetime
10
- from pathlib import Path
11
 
12
  from fastapi import FastAPI, UploadFile, File, Form, HTTPException
13
- from fastapi.responses import JSONResponse, FileResponse, HTMLResponse
14
  from fastapi.middleware.cors import CORSMiddleware
15
  import PyPDF2
16
  from youtube_transcript_api import YouTubeTranscriptApi
17
- import requests
18
 
19
  # Initialize FastAPI
20
  app = FastAPI(title="StudyFlow AI", version="1.0.0")
@@ -115,8 +113,6 @@ def init_db():
115
  total_questions INTEGER DEFAULT 0,
116
  correct_answers INTEGER DEFAULT 0,
117
  total_study_time INTEGER DEFAULT 0,
118
- weak_areas TEXT,
119
- strengths TEXT,
120
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
121
  )
122
  ''')
@@ -141,18 +137,17 @@ def extract_text_from_pdf(file_path: str) -> str:
141
  with open(file_path, 'rb') as file:
142
  pdf_reader = PyPDF2.PdfReader(file)
143
  text = ""
144
- for page in pdf_reader.pages:
145
  page_text = page.extract_text()
146
  if page_text:
147
  text += page_text + "\n"
148
- return text[:5000] # Limit text length
149
  except Exception as e:
150
- return f"PDF text extraction error: {str(e)}"
151
 
152
  def extract_text_from_youtube(url: str) -> str:
153
  """Extract transcript from YouTube video"""
154
  try:
155
- # Extract video ID from URL
156
  if "youtube.com/watch?v=" in url:
157
  video_id = url.split("v=")[-1].split("&")[0]
158
  elif "youtu.be/" in url:
@@ -162,28 +157,23 @@ def extract_text_from_youtube(url: str) -> str:
162
 
163
  transcript = YouTubeTranscriptApi.get_transcript(video_id)
164
  text = " ".join([entry['text'] for entry in transcript])
165
- return text[:5000] # Limit text length
166
  except Exception as e:
167
- return f"YouTube transcript error: {str(e)}"
168
 
169
  def generate_questions(text: str, difficulty: str, count: int = 5) -> list:
170
  """Generate questions from text"""
171
- # Split text into sentences
172
  import re
173
  sentences = re.split(r'[.!?]+', text)
174
- sentences = [s.strip() for s in sentences if len(s.strip()) > 30]
175
 
176
  if not sentences:
177
- sentences = [text[:200]] # Use first 200 chars as fallback
178
 
179
  questions = []
180
  for i, sentence in enumerate(sentences[:count]):
181
- if not sentence:
182
- continue
183
-
184
- qid = generate_id(f"q_{i}_{sentence[:20]}")
185
 
186
- # Simple question generation
187
  if difficulty == "easy":
188
  # Fill in the blank
189
  words = sentence.split()
@@ -197,43 +187,25 @@ def generate_questions(text: str, difficulty: str, count: int = 5) -> list:
197
  "question_type": "fill_blank",
198
  "correct_answer": blank_word,
199
  "difficulty": difficulty,
200
- "explanation": f"The missing word is '{blank_word}' which completes the sentence."
201
- })
202
- else:
203
- # Multiple choice for short sentences
204
- question_text = f"What is the meaning of: '{sentence}'?"
205
- options = ["A factual statement", "An opinion", "A question", "A command"]
206
- questions.append({
207
- "id": qid,
208
- "question_text": question_text,
209
- "question_type": "multiple_choice",
210
- "options": json.dumps(options),
211
- "correct_answer": "0",
212
- "difficulty": difficulty,
213
- "explanation": "This appears to be a factual statement."
214
  })
215
 
216
  elif difficulty == "medium":
217
- # True/False question
218
- question_text = f"Is the following statement true? '{sentence}'"
219
  questions.append({
220
  "id": qid,
221
  "question_text": question_text,
222
  "question_type": "true_false",
223
- "correct_answer": "0", # True
224
  "difficulty": difficulty,
225
- "explanation": "This statement appears to be true based on the context."
226
  })
227
 
228
  else: # hard
229
- # Multiple choice with context
230
- question_text = f"What is the main idea of: '{sentence[:150]}...'?"
231
- options = [
232
- "It describes a specific detail",
233
- "It presents a general concept",
234
- "It asks a rhetorical question",
235
- "It provides an example"
236
- ]
237
  questions.append({
238
  "id": qid,
239
  "question_text": question_text,
@@ -241,7 +213,7 @@ def generate_questions(text: str, difficulty: str, count: int = 5) -> list:
241
  "options": json.dumps(options),
242
  "correct_answer": "1",
243
  "difficulty": difficulty,
244
- "explanation": "This sentence appears to present a general concept rather than specific details."
245
  })
246
 
247
  return questions
@@ -255,25 +227,13 @@ def generate_flashcards(text: str, count: int = 3) -> list:
255
  flashcards = []
256
  for i in range(min(len(sentences), count)):
257
  sentence = sentences[i]
258
- if not sentence:
259
- continue
260
-
261
- fcid = generate_id(f"fc_{i}_{sentence[:20]}")
262
-
263
- # Create flashcard with term and definition
264
- words = sentence.split()
265
- if len(words) > 5:
266
- term = " ".join(words[:3]) + "..."
267
- definition = sentence
268
- else:
269
- term = sentence
270
- definition = "Key concept from the study material"
271
 
272
  flashcards.append({
273
  "id": fcid,
274
- "front": term[:100],
275
- "back": definition[:200],
276
- "category": "Study Material",
277
  "difficulty": "medium"
278
  })
279
 
@@ -289,14 +249,12 @@ async def process_content(
289
  file: UploadFile = File(None),
290
  youtube_url: str = Form(None)
291
  ):
292
- """Process uploaded content and create study materials"""
293
 
294
- # Extract text based on content type
295
  text_content = ""
296
  if content_type == "text" and content:
297
- text_content = content[:10000] # Limit length
298
  elif content_type == "pdf" and file:
299
- # Save uploaded file temporarily
300
  with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
301
  content_bytes = await file.read()
302
  temp_file.write(content_bytes)
@@ -307,87 +265,54 @@ async def process_content(
307
  elif content_type == "youtube" and youtube_url:
308
  text_content = extract_text_from_youtube(youtube_url)
309
  else:
310
- raise HTTPException(status_code=400, detail="Invalid content type or missing content")
311
 
312
  if len(text_content) < 50:
313
- raise HTTPException(status_code=400, detail="Content too short (minimum 50 characters)")
314
 
315
- # Generate content hash
316
  content_hash = hashlib.md5(text_content.encode()).hexdigest()
317
 
318
- # Check if session already exists
319
  conn = sqlite3.connect(DB_PATH)
320
  cursor = conn.cursor()
321
 
322
- cursor.execute(
323
- "SELECT id FROM sessions WHERE content_hash = ?",
324
- (content_hash,)
325
- )
326
  existing = cursor.fetchone()
327
 
328
  if existing:
329
  conn.close()
330
- return JSONResponse({
331
- "message": "Session already exists",
332
- "session_id": existing[0],
333
- "is_existing": True
334
- })
335
 
336
  # Create new session
337
  session_id = generate_id(text_content[:100])
338
 
339
- cursor.execute('''
340
- INSERT INTO sessions (id, title, content_type, difficulty, content_hash)
341
- VALUES (?, ?, ?, ?, ?)
342
- ''', (session_id, title, content_type, difficulty, content_hash))
343
 
344
- # Generate study materials
345
  questions = generate_questions(text_content, difficulty, 5)
346
  flashcards = generate_flashcards(text_content, 3)
347
 
348
  # Save questions
349
  for q in questions:
350
- cursor.execute('''
351
- INSERT INTO questions (id, session_id, question_text, question_type,
352
- options, correct_answer, difficulty, explanation)
353
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
354
- ''', (
355
- q["id"], session_id, q["question_text"], q["question_type"],
356
- q.get("options"), q["correct_answer"], q["difficulty"], q.get("explanation", "")
357
- ))
358
 
359
  # Save flashcards
360
  for fc in flashcards:
361
- cursor.execute('''
362
- INSERT INTO flashcards (id, session_id, front, back, category, difficulty)
363
- VALUES (?, ?, ?, ?, ?, ?)
364
- ''', (
365
- fc["id"], session_id, fc["front"], fc["back"],
366
- fc["category"], fc["difficulty"]
367
- ))
368
-
369
- # Create initial note
370
- note_id = generate_id(f"note_{session_id}")
371
- cursor.execute('''
372
- INSERT INTO notes (id, session_id, title, content)
373
- VALUES (?, ?, ?, ?)
374
- ''', (
375
- note_id,
376
- session_id,
377
- "Study Notes",
378
- f"Key points from: {title}\n\nSummary: {text_content[:500]}..."
379
- ))
380
 
381
  conn.commit()
382
  conn.close()
383
 
384
- return JSONResponse({
385
- "message": "Session created successfully",
386
- "session_id": session_id,
387
- "is_existing": False,
388
- "question_count": len(questions),
389
- "flashcard_count": len(flashcards)
390
- })
391
 
392
  @app.get("/api/session/{session_id}")
393
  async def get_session(session_id: str):
@@ -396,7 +321,6 @@ async def get_session(session_id: str):
396
  conn.row_factory = sqlite3.Row
397
  cursor = conn.cursor()
398
 
399
- # Get session info
400
  cursor.execute("SELECT * FROM sessions WHERE id = ?", (session_id,))
401
  session = cursor.fetchone()
402
 
@@ -405,24 +329,18 @@ async def get_session(session_id: str):
405
  raise HTTPException(status_code=404, detail="Session not found")
406
 
407
  # Update last accessed
408
- cursor.execute(
409
- "UPDATE sessions SET last_accessed = CURRENT_TIMESTAMP WHERE id = ?",
410
- (session_id,)
411
- )
412
 
413
- # Get questions
414
  cursor.execute("SELECT * FROM questions WHERE session_id = ?", (session_id,))
415
  questions = [dict(row) for row in cursor.fetchall()]
416
 
417
- # Get flashcards
418
  cursor.execute("SELECT * FROM flashcards WHERE session_id = ?", (session_id,))
419
  flashcards = [dict(row) for row in cursor.fetchall()]
420
 
421
- # Get notes
422
  cursor.execute("SELECT * FROM notes WHERE session_id = ?", (session_id,))
423
  notes = [dict(row) for row in cursor.fetchall()]
424
 
425
- # Get highlights
426
  cursor.execute("SELECT * FROM highlights WHERE session_id = ?", (session_id,))
427
  highlights = [dict(row) for row in cursor.fetchall()]
428
 
@@ -430,7 +348,6 @@ async def get_session(session_id: str):
430
  total_questions = len(questions)
431
  correct_answers = sum(1 for q in questions if q.get("is_correct") == 1)
432
  accuracy = round((correct_answers / total_questions * 100) if total_questions > 0 else 0, 1)
433
- avg_time_spent = round(sum(q.get("time_spent", 0) for q in questions) / total_questions if total_questions > 0 else 0, 1)
434
 
435
  conn.commit()
436
  conn.close()
@@ -453,7 +370,7 @@ async def get_session(session_id: str):
453
  "total_questions": total_questions,
454
  "correct_answers": correct_answers,
455
  "accuracy": accuracy,
456
- "avg_time_spent": avg_time_spent
457
  }
458
  }
459
 
@@ -467,7 +384,6 @@ async def get_user_sessions():
467
  cursor.execute("SELECT * FROM sessions ORDER BY last_accessed DESC")
468
  sessions = [dict(row) for row in cursor.fetchall()]
469
 
470
- # Add performance stats to each session
471
  for session in sessions:
472
  cursor.execute(
473
  "SELECT COUNT(*), SUM(is_correct) FROM questions WHERE session_id = ?",
@@ -478,11 +394,7 @@ async def get_user_sessions():
478
  correct = result[1] or 0
479
  accuracy = round((correct / total * 100) if total > 0 else 0, 1)
480
 
481
- session["performance"] = {
482
- "total": total,
483
- "correct": correct,
484
- "accuracy": accuracy
485
- }
486
 
487
  conn.close()
488
 
@@ -495,15 +407,11 @@ async def submit_answer(
495
  user_answer: str = Form(...),
496
  time_spent: int = Form(0)
497
  ):
498
- """Submit an answer to a question"""
499
  conn = sqlite3.connect(DB_PATH)
500
  cursor = conn.cursor()
501
 
502
- # Get correct answer
503
- cursor.execute(
504
- "SELECT correct_answer FROM questions WHERE id = ? AND session_id = ?",
505
- (question_id, session_id)
506
- )
507
  result = cursor.fetchone()
508
 
509
  if not result:
@@ -511,89 +419,48 @@ async def submit_answer(
511
  raise HTTPException(status_code=404, detail="Question not found")
512
 
513
  correct_answer = result[0]
 
514
 
515
- # Simple answer checking
516
- if isinstance(correct_answer, str) and correct_answer.isdigit():
517
- # Multiple choice or true/false
518
- is_correct = 1 if str(user_answer).strip() == str(correct_answer).strip() else 0
519
- else:
520
- # Fill in the blank - case insensitive partial match
521
- user_ans = str(user_answer).strip().lower()
522
- correct_ans = str(correct_answer).strip().lower()
523
- is_correct = 1 if user_ans == correct_ans or correct_ans in user_ans or user_ans in correct_ans else 0
524
-
525
- # Update question with user answer
526
- cursor.execute('''
527
- UPDATE questions
528
- SET user_answer = ?, is_correct = ?, time_spent = ?
529
- WHERE id = ? AND session_id = ?
530
- ''', (user_answer, is_correct, time_spent, question_id, session_id))
531
-
532
- # Update user profile stats
533
- cursor.execute('''
534
- INSERT OR IGNORE INTO user_profile (id) VALUES (1)
535
- ''')
536
 
537
- cursor.execute('''
538
- UPDATE user_profile
539
- SET total_questions = total_questions + 1,
540
- correct_answers = correct_answers + ?,
541
- updated_at = CURRENT_TIMESTAMP
542
- WHERE id = 1
543
- ''', (is_correct,))
544
 
545
  conn.commit()
546
  conn.close()
547
 
548
- return {
549
- "is_correct": bool(is_correct),
550
- "correct_answer": correct_answer,
551
- "message": "Correct! Well done!" if is_correct else "Incorrect. The correct answer was: " + str(correct_answer)
552
- }
553
 
554
  @app.post("/api/analyze-text")
555
  async def analyze_text(text: str = Form(...), session_id: str = Form(...)):
556
  """Analyze selected text"""
557
-
558
- if len(text) < 2 or len(text) > 1000:
559
- raise HTTPException(status_code=400, detail="Text must be between 2 and 1000 characters")
560
-
561
- # Simple text analysis
562
  words = text.split()
563
  definitions = []
564
 
565
- # Create simple definitions for longer words
566
- for i, word in enumerate(words[:min(5, len(words))]):
567
- if len(word) > 4 and word.isalpha():
568
  definitions.append({
569
  "word": word,
570
- "definition": f"'{word}' appears in this context. It's likely a key term in the study material.",
571
- "source": "StudyFlow AI Analysis",
572
- "example": f"Used in: '{' '.join(words[max(0,i-2):min(len(words),i+3)])}'"
573
  })
574
 
575
- # Generate explanation based on text length
576
- word_count = len(words)
577
- if word_count < 5:
578
- explanation = "This is a short phrase or term."
579
- elif word_count < 15:
580
- explanation = "This appears to be a complete sentence expressing a single idea."
581
- else:
582
- explanation = "This text contains multiple ideas or detailed information."
583
-
584
- # Count unique words
585
- unique_words = len(set([w.lower() for w in words if w.isalpha()]))
586
- explanation += f"\n\nIt contains {word_count} words with {unique_words} unique terms."
587
-
588
- # Save as highlight
589
  conn = sqlite3.connect(DB_PATH)
590
  cursor = conn.cursor()
591
 
592
  highlight_id = generate_id(text)
593
- cursor.execute('''
594
- INSERT OR IGNORE INTO highlights (id, session_id, text, context)
595
- VALUES (?, ?, ?, ?)
596
- ''', (highlight_id, session_id, text, json.dumps(definitions)))
597
 
598
  conn.commit()
599
  conn.close()
@@ -601,17 +468,13 @@ async def analyze_text(text: str = Form(...), session_id: str = Form(...)):
601
  return {
602
  "text": text,
603
  "definitions": definitions,
604
- "explanation": explanation,
605
- "suggested_actions": [
606
- "Create a flashcard for this concept",
607
- "Generate a practice question",
608
- "Add to study notes"
609
- ]
610
  }
611
 
612
  @app.get("/api/user/profile")
613
  async def get_user_profile():
614
- """Get user learning profile"""
615
  conn = sqlite3.connect(DB_PATH)
616
  cursor = conn.cursor()
617
 
@@ -619,68 +482,33 @@ async def get_user_profile():
619
  profile = cursor.fetchone()
620
 
621
  if not profile:
622
- # Create default profile
623
- cursor.execute('''
624
- INSERT INTO user_profile (id) VALUES (1)
625
- ''')
626
  conn.commit()
627
  cursor.execute("SELECT * FROM user_profile WHERE id = 1")
628
  profile = cursor.fetchone()
629
 
630
- # Get insights from questions
631
- cursor.execute('''
632
- SELECT difficulty,
633
- COUNT(*) as total,
634
- SUM(is_correct) as correct
635
- FROM questions
636
- WHERE user_answer IS NOT NULL
637
- GROUP BY difficulty
638
- ''')
639
- difficulty_stats = cursor.fetchall()
640
-
641
- # Determine weak areas and strengths
642
- weak_areas = []
643
- strengths = []
644
-
645
- for diff, total, correct in difficulty_stats:
646
- if total > 0:
647
- accuracy = correct / total
648
- if accuracy < 0.5:
649
- weak_areas.append(f"{diff} difficulty questions")
650
- elif accuracy > 0.8:
651
- strengths.append(f"{diff} difficulty questions")
652
-
653
- # If no data yet
654
- if not weak_areas:
655
- weak_areas = ["Concepts will appear as you answer questions"]
656
- if not strengths:
657
- strengths = ["Keep practicing to build your strengths!"]
658
 
659
  conn.close()
660
 
661
  return {
662
  "profile": {
663
- "total_questions": profile[1] or 0,
664
- "correct_answers": profile[2] or 0,
665
  "total_study_time": profile[3] or 0,
666
- "accuracy": round((profile[2] / profile[1] * 100) if profile[1] and profile[1] > 0 else 0, 1)
667
  },
668
  "insights": {
669
- "weaknesses": weak_areas,
670
- "strengths": strengths,
671
- "recent_performance": [
672
- {
673
- "date": datetime.now().strftime("%Y-%m-%d"),
674
- "total": profile[1] or 0,
675
- "correct": profile[2] or 0
676
- }
677
- ]
678
  }
679
  }
680
 
681
  @app.delete("/api/session/{session_id}")
682
  async def delete_session(session_id: str):
683
- """Delete a session"""
684
  conn = sqlite3.connect(DB_PATH)
685
  cursor = conn.cursor()
686
 
@@ -693,61 +521,47 @@ async def delete_session(session_id: str):
693
  if affected == 0:
694
  raise HTTPException(status_code=404, detail="Session not found")
695
 
696
- return {"message": "Session deleted successfully"}
697
 
698
  @app.post("/api/update-study-time")
699
  async def update_study_time(session_id: str = Form(...), study_time: int = Form(...)):
700
- """Update study time for a session"""
701
  conn = sqlite3.connect(DB_PATH)
702
  cursor = conn.cursor()
703
 
704
- cursor.execute('''
705
- UPDATE sessions
706
- SET last_accessed = CURRENT_TIMESTAMP
707
- WHERE id = ?
708
- ''', (session_id,))
709
-
710
- cursor.execute('''
711
- INSERT OR IGNORE INTO user_profile (id) VALUES (1)
712
- ''')
713
-
714
- cursor.execute('''
715
- UPDATE user_profile
716
- SET total_study_time = COALESCE(total_study_time, 0) + ?
717
- WHERE id = 1
718
- ''', (study_time,))
719
 
720
  conn.commit()
721
  conn.close()
722
 
723
  return {"message": "Study time updated"}
724
 
725
- # Health check endpoint
726
- @app.get("/health")
727
- async def health_check():
728
- """Health check endpoint"""
729
- return {"status": "healthy", "timestamp": datetime.now().isoformat()}
730
-
731
- # Serve frontend files
732
  @app.get("/")
733
  async def serve_frontend():
734
  """Serve the main frontend page"""
735
  try:
736
- with open("index.html", "r", encoding="utf-8") as f:
737
- html_content = f.read()
738
- return HTMLResponse(content=html_content)
739
- except FileNotFoundError:
740
- return HTMLResponse(content="<h1>StudyFlow AI Backend is running!</h1><p>Frontend files not found.</p>")
741
 
742
  @app.get("/app.js")
743
  async def serve_js():
744
- """Serve the JavaScript file"""
745
  try:
746
- with open("app.js", "r", encoding="utf-8") as f:
747
- js_content = f.read()
748
- return HTMLResponse(content=js_content, media_type="application/javascript")
749
- except FileNotFoundError:
750
- return HTMLResponse(content="console.error('app.js not found');", media_type="application/javascript")
 
 
 
751
 
752
  if __name__ == "__main__":
753
  import uvicorn
 
1
  """
2
+ StudyFlow AI Backend - Complete Working Version
3
  """
4
  import os
5
  import json
 
7
  import hashlib
8
  import tempfile
9
  from datetime import datetime
 
10
 
11
  from fastapi import FastAPI, UploadFile, File, Form, HTTPException
12
+ from fastapi.responses import JSONResponse, HTMLResponse
13
  from fastapi.middleware.cors import CORSMiddleware
14
  import PyPDF2
15
  from youtube_transcript_api import YouTubeTranscriptApi
 
16
 
17
  # Initialize FastAPI
18
  app = FastAPI(title="StudyFlow AI", version="1.0.0")
 
113
  total_questions INTEGER DEFAULT 0,
114
  correct_answers INTEGER DEFAULT 0,
115
  total_study_time INTEGER DEFAULT 0,
 
 
116
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
117
  )
118
  ''')
 
137
  with open(file_path, 'rb') as file:
138
  pdf_reader = PyPDF2.PdfReader(file)
139
  text = ""
140
+ for page in pdf_reader.pages[:10]: # Limit to first 10 pages
141
  page_text = page.extract_text()
142
  if page_text:
143
  text += page_text + "\n"
144
+ return text[:10000] # Limit text length
145
  except Exception as e:
146
+ return f"PDF extraction: {str(e)}"
147
 
148
  def extract_text_from_youtube(url: str) -> str:
149
  """Extract transcript from YouTube video"""
150
  try:
 
151
  if "youtube.com/watch?v=" in url:
152
  video_id = url.split("v=")[-1].split("&")[0]
153
  elif "youtu.be/" in url:
 
157
 
158
  transcript = YouTubeTranscriptApi.get_transcript(video_id)
159
  text = " ".join([entry['text'] for entry in transcript])
160
+ return text[:10000] # Limit text length
161
  except Exception as e:
162
+ return f"YouTube: {str(e)}"
163
 
164
  def generate_questions(text: str, difficulty: str, count: int = 5) -> list:
165
  """Generate questions from text"""
 
166
  import re
167
  sentences = re.split(r'[.!?]+', text)
168
+ sentences = [s.strip() for s in sentences if len(s.strip()) > 20]
169
 
170
  if not sentences:
171
+ sentences = [text[:200]]
172
 
173
  questions = []
174
  for i, sentence in enumerate(sentences[:count]):
175
+ qid = generate_id(f"q_{i}")
 
 
 
176
 
 
177
  if difficulty == "easy":
178
  # Fill in the blank
179
  words = sentence.split()
 
187
  "question_type": "fill_blank",
188
  "correct_answer": blank_word,
189
  "difficulty": difficulty,
190
+ "explanation": f"The answer is '{blank_word}'"
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  })
192
 
193
  elif difficulty == "medium":
194
+ # True/False
195
+ question_text = f"True or False: '{sentence}'"
196
  questions.append({
197
  "id": qid,
198
  "question_text": question_text,
199
  "question_type": "true_false",
200
+ "correct_answer": "0",
201
  "difficulty": difficulty,
202
+ "explanation": "This statement appears to be true."
203
  })
204
 
205
  else: # hard
206
+ # Multiple choice
207
+ question_text = f"What is the main idea? '{sentence[:100]}...'"
208
+ options = ["Detail", "Concept", "Question", "Example"]
 
 
 
 
 
209
  questions.append({
210
  "id": qid,
211
  "question_text": question_text,
 
213
  "options": json.dumps(options),
214
  "correct_answer": "1",
215
  "difficulty": difficulty,
216
+ "explanation": "This presents a general concept."
217
  })
218
 
219
  return questions
 
227
  flashcards = []
228
  for i in range(min(len(sentences), count)):
229
  sentence = sentences[i]
230
+ fcid = generate_id(f"fc_{i}")
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
  flashcards.append({
233
  "id": fcid,
234
+ "front": sentence[:100],
235
+ "back": f"Explanation of: {sentence[:50]}...",
236
+ "category": "Study",
237
  "difficulty": "medium"
238
  })
239
 
 
249
  file: UploadFile = File(None),
250
  youtube_url: str = Form(None)
251
  ):
252
+ """Process uploaded content"""
253
 
 
254
  text_content = ""
255
  if content_type == "text" and content:
256
+ text_content = content[:10000]
257
  elif content_type == "pdf" and file:
 
258
  with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
259
  content_bytes = await file.read()
260
  temp_file.write(content_bytes)
 
265
  elif content_type == "youtube" and youtube_url:
266
  text_content = extract_text_from_youtube(youtube_url)
267
  else:
268
+ raise HTTPException(status_code=400, detail="Invalid content")
269
 
270
  if len(text_content) < 50:
271
+ raise HTTPException(status_code=400, detail="Content too short")
272
 
 
273
  content_hash = hashlib.md5(text_content.encode()).hexdigest()
274
 
 
275
  conn = sqlite3.connect(DB_PATH)
276
  cursor = conn.cursor()
277
 
278
+ # Check if exists
279
+ cursor.execute("SELECT id FROM sessions WHERE content_hash = ?", (content_hash,))
 
 
280
  existing = cursor.fetchone()
281
 
282
  if existing:
283
  conn.close()
284
+ return {"session_id": existing[0], "is_existing": True}
 
 
 
 
285
 
286
  # Create new session
287
  session_id = generate_id(text_content[:100])
288
 
289
+ cursor.execute(
290
+ "INSERT INTO sessions (id, title, content_type, difficulty, content_hash) VALUES (?, ?, ?, ?, ?)",
291
+ (session_id, title, content_type, difficulty, content_hash)
292
+ )
293
 
294
+ # Generate materials
295
  questions = generate_questions(text_content, difficulty, 5)
296
  flashcards = generate_flashcards(text_content, 3)
297
 
298
  # Save questions
299
  for q in questions:
300
+ cursor.execute(
301
+ "INSERT INTO questions (id, session_id, question_text, question_type, options, correct_answer, difficulty, explanation) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
302
+ (q["id"], session_id, q["question_text"], q["question_type"], q.get("options"), q["correct_answer"], q["difficulty"], q.get("explanation", ""))
303
+ )
 
 
 
 
304
 
305
  # Save flashcards
306
  for fc in flashcards:
307
+ cursor.execute(
308
+ "INSERT INTO flashcards (id, session_id, front, back, category, difficulty) VALUES (?, ?, ?, ?, ?, ?)",
309
+ (fc["id"], session_id, fc["front"], fc["back"], fc["category"], fc["difficulty"])
310
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
 
312
  conn.commit()
313
  conn.close()
314
 
315
+ return {"session_id": session_id, "is_existing": False}
 
 
 
 
 
 
316
 
317
  @app.get("/api/session/{session_id}")
318
  async def get_session(session_id: str):
 
321
  conn.row_factory = sqlite3.Row
322
  cursor = conn.cursor()
323
 
 
324
  cursor.execute("SELECT * FROM sessions WHERE id = ?", (session_id,))
325
  session = cursor.fetchone()
326
 
 
329
  raise HTTPException(status_code=404, detail="Session not found")
330
 
331
  # Update last accessed
332
+ cursor.execute("UPDATE sessions SET last_accessed = CURRENT_TIMESTAMP WHERE id = ?", (session_id,))
 
 
 
333
 
334
+ # Get materials
335
  cursor.execute("SELECT * FROM questions WHERE session_id = ?", (session_id,))
336
  questions = [dict(row) for row in cursor.fetchall()]
337
 
 
338
  cursor.execute("SELECT * FROM flashcards WHERE session_id = ?", (session_id,))
339
  flashcards = [dict(row) for row in cursor.fetchall()]
340
 
 
341
  cursor.execute("SELECT * FROM notes WHERE session_id = ?", (session_id,))
342
  notes = [dict(row) for row in cursor.fetchall()]
343
 
 
344
  cursor.execute("SELECT * FROM highlights WHERE session_id = ?", (session_id,))
345
  highlights = [dict(row) for row in cursor.fetchall()]
346
 
 
348
  total_questions = len(questions)
349
  correct_answers = sum(1 for q in questions if q.get("is_correct") == 1)
350
  accuracy = round((correct_answers / total_questions * 100) if total_questions > 0 else 0, 1)
 
351
 
352
  conn.commit()
353
  conn.close()
 
370
  "total_questions": total_questions,
371
  "correct_answers": correct_answers,
372
  "accuracy": accuracy,
373
+ "avg_time_spent": 0
374
  }
375
  }
376
 
 
384
  cursor.execute("SELECT * FROM sessions ORDER BY last_accessed DESC")
385
  sessions = [dict(row) for row in cursor.fetchall()]
386
 
 
387
  for session in sessions:
388
  cursor.execute(
389
  "SELECT COUNT(*), SUM(is_correct) FROM questions WHERE session_id = ?",
 
394
  correct = result[1] or 0
395
  accuracy = round((correct / total * 100) if total > 0 else 0, 1)
396
 
397
+ session["performance"] = {"total": total, "correct": correct, "accuracy": accuracy}
 
 
 
 
398
 
399
  conn.close()
400
 
 
407
  user_answer: str = Form(...),
408
  time_spent: int = Form(0)
409
  ):
410
+ """Submit an answer"""
411
  conn = sqlite3.connect(DB_PATH)
412
  cursor = conn.cursor()
413
 
414
+ cursor.execute("SELECT correct_answer FROM questions WHERE id = ? AND session_id = ?", (question_id, session_id))
 
 
 
 
415
  result = cursor.fetchone()
416
 
417
  if not result:
 
419
  raise HTTPException(status_code=404, detail="Question not found")
420
 
421
  correct_answer = result[0]
422
+ is_correct = 1 if str(user_answer).strip().lower() == str(correct_answer).strip().lower() else 0
423
 
424
+ cursor.execute(
425
+ "UPDATE questions SET user_answer = ?, is_correct = ?, time_spent = ? WHERE id = ? AND session_id = ?",
426
+ (user_answer, is_correct, time_spent, question_id, session_id)
427
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
 
429
+ # Update profile
430
+ cursor.execute("INSERT OR IGNORE INTO user_profile (id) VALUES (1)")
431
+ cursor.execute(
432
+ "UPDATE user_profile SET total_questions = total_questions + 1, correct_answers = correct_answers + ? WHERE id = 1",
433
+ (is_correct,)
434
+ )
 
435
 
436
  conn.commit()
437
  conn.close()
438
 
439
+ return {"is_correct": bool(is_correct), "correct_answer": correct_answer}
 
 
 
 
440
 
441
  @app.post("/api/analyze-text")
442
  async def analyze_text(text: str = Form(...), session_id: str = Form(...)):
443
  """Analyze selected text"""
 
 
 
 
 
444
  words = text.split()
445
  definitions = []
446
 
447
+ for word in words[:3]:
448
+ if len(word) > 3:
 
449
  definitions.append({
450
  "word": word,
451
+ "definition": f"Key term in context",
452
+ "example": f"Used in: '{text[:50]}...'"
 
453
  })
454
 
455
+ # Save highlight
 
 
 
 
 
 
 
 
 
 
 
 
 
456
  conn = sqlite3.connect(DB_PATH)
457
  cursor = conn.cursor()
458
 
459
  highlight_id = generate_id(text)
460
+ cursor.execute(
461
+ "INSERT OR IGNORE INTO highlights (id, session_id, text, context) VALUES (?, ?, ?, ?)",
462
+ (highlight_id, session_id, text, json.dumps(definitions))
463
+ )
464
 
465
  conn.commit()
466
  conn.close()
 
468
  return {
469
  "text": text,
470
  "definitions": definitions,
471
+ "explanation": f"Analysis of selected text ({len(words)} words)",
472
+ "suggested_actions": ["Create flashcard", "Add to notes"]
 
 
 
 
473
  }
474
 
475
  @app.get("/api/user/profile")
476
  async def get_user_profile():
477
+ """Get user profile"""
478
  conn = sqlite3.connect(DB_PATH)
479
  cursor = conn.cursor()
480
 
 
482
  profile = cursor.fetchone()
483
 
484
  if not profile:
485
+ cursor.execute("INSERT INTO user_profile (id) VALUES (1)")
 
 
 
486
  conn.commit()
487
  cursor.execute("SELECT * FROM user_profile WHERE id = 1")
488
  profile = cursor.fetchone()
489
 
490
+ total = profile[1] or 0
491
+ correct = profile[2] or 0
492
+ accuracy = round((correct / total * 100) if total > 0 else 0, 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
493
 
494
  conn.close()
495
 
496
  return {
497
  "profile": {
498
+ "total_questions": total,
499
+ "correct_answers": correct,
500
  "total_study_time": profile[3] or 0,
501
+ "accuracy": accuracy
502
  },
503
  "insights": {
504
+ "weaknesses": ["Practice more to identify areas"],
505
+ "strengths": ["Getting started is the first step!"]
 
 
 
 
 
 
 
506
  }
507
  }
508
 
509
  @app.delete("/api/session/{session_id}")
510
  async def delete_session(session_id: str):
511
+ """Delete session"""
512
  conn = sqlite3.connect(DB_PATH)
513
  cursor = conn.cursor()
514
 
 
521
  if affected == 0:
522
  raise HTTPException(status_code=404, detail="Session not found")
523
 
524
+ return {"message": "Session deleted"}
525
 
526
  @app.post("/api/update-study-time")
527
  async def update_study_time(session_id: str = Form(...), study_time: int = Form(...)):
528
+ """Update study time"""
529
  conn = sqlite3.connect(DB_PATH)
530
  cursor = conn.cursor()
531
 
532
+ cursor.execute("UPDATE sessions SET last_accessed = CURRENT_TIMESTAMP WHERE id = ?", (session_id,))
533
+ cursor.execute("INSERT OR IGNORE INTO user_profile (id) VALUES (1)")
534
+ cursor.execute(
535
+ "UPDATE user_profile SET total_study_time = COALESCE(total_study_time, 0) + ? WHERE id = 1",
536
+ (study_time,)
537
+ )
 
 
 
 
 
 
 
 
 
538
 
539
  conn.commit()
540
  conn.close()
541
 
542
  return {"message": "Study time updated"}
543
 
544
+ # Serve frontend
 
 
 
 
 
 
545
  @app.get("/")
546
  async def serve_frontend():
547
  """Serve the main frontend page"""
548
  try:
549
+ return HTMLResponse(content=open("index.html").read())
550
+ except:
551
+ return HTMLResponse(content="<h1>StudyFlow AI Backend Running</h1>")
 
 
552
 
553
  @app.get("/app.js")
554
  async def serve_js():
555
+ """Serve JavaScript"""
556
  try:
557
+ return HTMLResponse(content=open("app.js").read(), media_type="application/javascript")
558
+ except:
559
+ return HTMLResponse(content="console.log('JS loaded');", media_type="application/javascript")
560
+
561
+ # Health check
562
+ @app.get("/health")
563
+ async def health_check():
564
+ return {"status": "healthy", "timestamp": datetime.now().isoformat()}
565
 
566
  if __name__ == "__main__":
567
  import uvicorn