ankban commited on
Commit
bdda033
·
verified ·
1 Parent(s): 001a676

Update file_utils.py

Browse files
Files changed (1) hide show
  1. file_utils.py +101 -18
file_utils.py CHANGED
@@ -1,24 +1,107 @@
1
- import gradio as gr
2
- from file_study_guide_panel import file_study_guide_dashboard
 
 
 
 
 
 
3
 
4
- def file_based_learning_router():
5
- with gr.Column(scale=4, elem_id="main-column") as router:
6
- view = gr.State("study") # default view
 
7
 
8
- file_view_panel = gr.Column(visible=False)
9
- file_study_panel = gr.Column(visible=True)
10
 
11
- with file_study_panel:
12
- file_study_guide_dashboard()
 
 
 
 
 
13
 
14
- with file_view_panel:
15
- file_viewer_dashboard()
 
 
 
 
 
 
 
 
 
 
16
 
17
- def show_view(mode):
18
- return (
19
- gr.update(visible=(mode == "study")),
20
- gr.update(visible=(mode == "file")),
21
- mode
22
- )
23
 
24
- return router, show_view, file_study_panel, file_view_panel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlmodel import SQLModel, Field, create_engine, Session, select
2
+ from datetime import datetime
3
+ from typing import Optional
4
+ import os
5
+ import json
6
+ from pptx import Presentation
7
+ import fitz # PyMuPDF
8
+ from openai import OpenAI
9
 
10
+ # === Setup ===
11
+ db_path = "/tmp/chatter_sessions.db"
12
+ engine = create_engine(f"sqlite:///{db_path}")
13
+ SQLModel.metadata.create_all(engine)
14
 
15
+ openai_api_key = os.getenv("OPENAI_API_KEY")
16
+ client = OpenAI(api_key=openai_api_key)
17
 
18
+ # === DB Table for Study Guides ===
19
+ class StudyGuideEntry(SQLModel, table=True):
20
+ id: Optional[int] = Field(default=None, primary_key=True)
21
+ user: str
22
+ filename: str
23
+ guide: str
24
+ timestamp: str
25
 
26
+ # === DB Utilities ===
27
+ def save_study_guide(user, filename, guide):
28
+ session = Session(engine)
29
+ entry = StudyGuideEntry(
30
+ user=user,
31
+ filename=filename,
32
+ guide=guide,
33
+ timestamp=datetime.now().strftime("%Y-%m-%d %H:%M")
34
+ )
35
+ session.add(entry)
36
+ session.commit()
37
+ session.close()
38
 
39
+ def fetch_study_guides(user):
40
+ session = Session(engine)
41
+ statement = select(StudyGuideEntry).where(StudyGuideEntry.user == user)
42
+ results = session.exec(statement).all()
43
+ session.close()
44
+ return results
45
 
46
+ # === GPT Utility ===
47
+ def call_llm(prompt, system_message="You are a helpful AI tutor."):
48
+ approx_tokens = len(prompt) // 4
49
+ if approx_tokens > 7000:
50
+ prompt = prompt[:28000] + "\n\n[Truncated for token limit]"
51
+
52
+ response = client.chat.completions.create(
53
+ model="gpt-4",
54
+ messages=[
55
+ {"role": "system", "content": system_message},
56
+ {"role": "user", "content": prompt}
57
+ ],
58
+ temperature=0.7
59
+ )
60
+ return response.choices[0].message.content
61
+
62
+ # === File Parsing ===
63
+ def extract_text_from_file(file):
64
+ ext = os.path.splitext(file.name)[1].lower()
65
+
66
+ if ext == ".pdf":
67
+ with fitz.open(file.name) as doc:
68
+ return "\n".join([page.get_text() for page in doc])
69
+
70
+ elif ext in [".txt", ".md"]:
71
+ return file.read().decode("utf-8")
72
+
73
+ elif ext == ".pptx":
74
+ prs = Presentation(file.name)
75
+ return "\n".join([
76
+ shape.text for slide in prs.slides for shape in slide.shapes if hasattr(shape, "text")
77
+ ])
78
+
79
+ else:
80
+ return "Unsupported file type."
81
+
82
+ # === GPT-Based Generators ===
83
+
84
+ def generate_summary(text):
85
+ prompt = f"Summarize the following document in 5–7 bullet points:\n\n{text}"
86
+ return call_llm(prompt)
87
+
88
+ def generate_flashcards(text):
89
+ prompt = f"Generate 5 flashcards based on this document. Each flashcard should follow this format:\nQ: ...\nA: ...\n\n{text}"
90
+ return call_llm(prompt)
91
+
92
+ def generate_quiz(text):
93
+ prompt = (
94
+ "Generate 5 multiple choice questions based on the document below. "
95
+ "Return the result as a JSON array where each item has:\n"
96
+ "- question (string)\n- options (list of strings)\n- answer (correct option string)\n\n"
97
+ f"{text}"
98
+ )
99
+ response = call_llm(prompt)
100
+ try:
101
+ return json.loads(response)
102
+ except:
103
+ return []
104
+
105
+ def answer_question(text, question):
106
+ prompt = f"Using only the document below, answer this question:\n\nDocument:\n{text}\n\nQuestion:\n{question}"
107
+ return call_llm(prompt)