ankban commited on
Commit
5a56bb7
·
verified ·
1 Parent(s): 78c47da

Update file_utils.py

Browse files
Files changed (1) hide show
  1. file_utils.py +102 -66
file_utils.py CHANGED
@@ -1,69 +1,105 @@
1
- import gradio as gr
 
 
2
  import os
3
 
 
 
4
 
5
- def file_dashboard():
6
- with gr.Column(elem_classes="file-panel") as file_panel:
7
- gr.Markdown("""
8
- <div style='text-align: center; margin-bottom: 1rem;'>
9
- <img src='file/images/chatter_owl.png' width='100'>
10
- <h2 style='margin-top: 0.5rem;'>📄 File-Based Learning with <strong>Chatter the Owl</strong></h2>
11
- <p style='margin-bottom: 1rem;'>Upload your notes, textbooks, or slides, and let me turn them into summaries, quizzes, and flashcards!</p>
12
- </div>
13
- """)
14
-
15
- file_upload = gr.File(label="📁 Upload Your Study Material", file_types=[".pdf", ".txt", ".md", ".pptx"])
16
- question_box = gr.Textbox(label="💬 Ask a question about the uploaded file", lines=2)
17
-
18
- with gr.Tabs():
19
- with gr.Tab("📚 Summary"):
20
- summary_output = gr.Textbox(label="Generated Summary", lines=6, interactive=False)
21
-
22
- with gr.Tab("🧠 Flashcards"):
23
- with gr.Accordion("Click to view generated flashcards", open=False):
24
- flashcard_output = gr.Textbox(label=None, lines=6, interactive=False, show_label=False)
25
-
26
- with gr.Tab("❓ Quiz"):
27
- with gr.Accordion("Click to view generated quiz questions", open=False):
28
- quiz_output = gr.Textbox(label=None, lines=6, interactive=False, show_label=False)
29
-
30
- with gr.Tab("💬 Answer to Your Question"):
31
- answer_output = gr.Textbox(label="Answer", lines=4, interactive=False)
32
-
33
- text_state = gr.State("")
34
-
35
- def handle_file_upload(file):
36
- if file is None:
37
- return "", "No file uploaded.", "", "", ""
38
-
39
- text = extract_text_from_file(file)
40
- if not text or "Unsupported file type" in text:
41
- return "", text, "", "", ""
42
-
43
- summary = generate_summary(text)
44
- flashcards = generate_flashcards(text)
45
- quiz = generate_quiz(text)
46
- return text, summary, flashcards, quiz, ""
47
-
48
- def handle_question(text, question):
49
- if not text.strip():
50
- return "Please upload a file first."
51
- if not question.strip():
52
- return "Please enter a question."
53
- return answer_question(text, question)
54
-
55
- file_upload.change(
56
- fn=handle_file_upload,
57
- inputs=[file_upload],
58
- outputs=[text_state, summary_output, flashcard_output, quiz_output, answer_output],
59
- show_progress="minimal"
60
- )
61
-
62
- question_box.change(
63
- fn=handle_question,
64
- inputs=[text_state, question_box],
65
- outputs=[answer_output],
66
- show_progress="minimal"
67
- )
68
-
69
- return file_panel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fitz # PyMuPDF
2
+ from pptx import Presentation
3
+ from openai import OpenAI
4
  import os
5
 
6
+ # === GPT-4 Client Setup ===
7
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
8
 
9
+ # === Centralized LLM Caller ===
10
+ def call_llm(prompt, system_message="You are a helpful assistant.", temperature=0.7):
11
+ response = client.chat.completions.create(
12
+ model="gpt-4",
13
+ messages=[
14
+ {"role": "system", "content": system_message},
15
+ {"role": "user", "content": prompt}
16
+ ],
17
+ temperature=temperature
18
+ )
19
+ return response.choices[0].message.content
20
+
21
+ # === File Parsers ===
22
+ def extract_text_from_pdf(pdf_path):
23
+ text = ""
24
+ with fitz.open(pdf_path) as doc:
25
+ for page in doc:
26
+ text += page.get_text()
27
+ return text
28
+
29
+
30
+ def extract_text_from_txt(file_path):
31
+ with open(file_path, 'r', encoding='utf-8') as f:
32
+ return f.read()
33
+
34
+
35
+ def extract_text_from_md(file_path):
36
+ with open(file_path, 'r', encoding='utf-8') as f:
37
+ return f.read()
38
+
39
+
40
+ def extract_text_from_pptx(file_path):
41
+ text = ""
42
+ prs = Presentation(file_path)
43
+ for slide in prs.slides:
44
+ for shape in slide.shapes:
45
+ if hasattr(shape, "text"):
46
+ text += shape.text + "\n"
47
+ return text
48
+
49
+
50
+ def extract_text_from_file(file):
51
+ if file is None:
52
+ return ""
53
+
54
+ name = file.name.lower()
55
+ if name.endswith(".pdf"):
56
+ return extract_text_from_pdf(file.name)
57
+ elif name.endswith(".txt"):
58
+ return extract_text_from_txt(file.name)
59
+ elif name.endswith(".md"):
60
+ return extract_text_from_md(file.name)
61
+ elif name.endswith(".pptx"):
62
+ return extract_text_from_pptx(file.name)
63
+ else:
64
+ return "Unsupported file type."
65
+
66
+
67
+ # === GPT-4 Powered Content Generators ===
68
+ def generate_summary(text):
69
+ prompt = f"""Please summarize the following study material in a concise and organized manner:
70
+
71
+ {text}
72
+ """
73
+ return call_llm(prompt, system_message="You are a helpful study assistant.")
74
+
75
+
76
+ def generate_flashcards(text):
77
+ prompt = f"""Based on the content below, create a set of helpful flashcards.
78
+ Each flashcard should be formatted as:
79
+ Q: Question?
80
+ A: Answer.
81
+
82
+ {text}
83
+ """
84
+ return call_llm(prompt, system_message="You are a flashcard generator assistant.")
85
+
86
+
87
+ def generate_quiz(text):
88
+ prompt = f"""Create a short quiz (3-5 questions) based on the content below.
89
+ Include a mix of multiple choice and short answer questions.
90
+
91
+ {text}
92
+ """
93
+ return call_llm(prompt, system_message="You are a quiz generator assistant.")
94
+
95
+
96
+ def answer_question(text, question):
97
+ prompt = f"""You are an AI tutor. Answer the following question based only on the content below.
98
+
99
+ Content:
100
+ {text}
101
+
102
+ Question:
103
+ {question}
104
+ """
105
+ return call_llm(prompt, system_message="You are a helpful and accurate tutor that stays grounded in provided content.")