Update file_utils.py
Browse files- file_utils.py +101 -18
file_utils.py
CHANGED
|
@@ -1,24 +1,107 @@
|
|
| 1 |
-
import
|
| 2 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|