SlouchyBuffalo commited on
Commit
c4c2bb4
Β·
verified Β·
1 Parent(s): 8b047e5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -0
app.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import spaces
3
+ from huggingface_hub import InferenceClient
4
+ import fitz # PyMuPDF for PDF processing
5
+ import docx
6
+ import os
7
+
8
+ # Initialize the Llama 4 model client
9
+ model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"
10
+ client = InferenceClient(model=model_id)
11
+
12
+ # Define the six prompt templates
13
+ PROMPTS = {
14
+ "summaries": """Write a concise summary of the provided document. The summary should be 150–200 words, capturing the main ideas, key arguments, or findings, and central themes. Exclude minor details or examples unless critical to the core message. Use clear, neutral language, structuring the summary with an introductory sentence stating the document's purpose, followed by main points in a logical order. Conclude with a brief statement on the document's significance or broader implications. Ensure accuracy by directly referencing the document's content and avoid personal opinions.
15
+
16
+ Document content:
17
+ {content}""",
18
+
19
+ "outlines": """Create a detailed outline of the provided document. The outline should feature a clear hierarchy with main sections, subsections, and bullet points summarizing key concepts, arguments, or findings under each. Use Roman numerals for main sections and letters or numbers for subsections. Include a brief introductory statement (50–100 words) describing the document's scope and purpose. Ensure the outline is comprehensive, logically organized, and captures all major points from the document without extraneous details.
20
+
21
+ Document content:
22
+ {content}""",
23
+
24
+ "analysis": """Provide a critical analysis of the provided document, focusing on its main arguments, evidence, or methodology. The analysis should be 300–400 words, evaluating strengths and weaknesses, the author's assumptions, biases, or rhetorical strategies, and the document's relevance or impact in its field or broader context. Support your points with direct evidence from the document, such as quotes or data. Organize the analysis with an introduction, body paragraphs (strengths, weaknesses, implications), and a conclusion. Maintain an objective tone, avoiding excessive summarization, and ensure all claims are grounded in the document's content.
25
+
26
+ Document content:
27
+ {content}""",
28
+
29
+ "study_guides": """Develop a comprehensive study guide for the provided document. The guide should include: (1) a brief overview (50–100 words) of the document's scope and purpose, (2) a list of 5–7 key themes or concepts with concise explanations (50–100 words each), (3) a glossary of 10–15 essential terms from the document with clear definitions, (4) 3–5 critical discussion questions to encourage deeper thinking, and (5) a checklist of key takeaways or study tips. Organize the guide with clear headings and bullet points, ensuring it is student-friendly and focused on retention and understanding.
30
+
31
+ Document content:
32
+ {content}""",
33
+
34
+ "tables": """Create a comparative table based on the provided document, synthesizing key elements (e.g., theories, findings, arguments, or concepts) across relevant criteria (e.g., assumptions, applications, strengths, weaknesses). The table should compare 3–5 elements, using rows for each element and columns for each criterion. Include a brief introductory paragraph (50–100 words) explaining the table's purpose and scope. Ensure the table is concise, visually organized, and populated with precise information directly from the document.
35
+
36
+ Document content:
37
+ {content}""",
38
+
39
+ "questions": """Generate a set of 10 high-quality questions based on the provided document. Include: (1) 3 factual questions to test recall of key details, (2) 3 conceptual questions to assess understanding of main ideas or arguments, (3) 2 analytical questions to encourage critical thinking about the document's implications or weaknesses, and (4) 2 open-ended questions to prompt discussion or creative reflection. Label each question by type (factual, conceptual, analytical, open-ended), and ensure questions are clear, specific, and aligned with the document's core themes.
40
+
41
+ Document content:
42
+ {content}"""
43
+ }
44
+
45
+ # Document processing functions
46
+ def extract_text_from_pdf(file_path):
47
+ """Extract text from PDF file"""
48
+ doc = fitz.open(file_path)
49
+ text = ""
50
+ for page in doc:
51
+ text += page.get_text()
52
+ doc.close()
53
+ return text
54
+
55
+ def extract_text_from_docx(file_path):
56
+ """Extract text from DOCX file"""
57
+ doc = docx.Document(file_path)
58
+ text = ""
59
+ for paragraph in doc.paragraphs:
60
+ text += paragraph.text + "\n"
61
+ return text
62
+
63
+ def extract_text_from_txt(file_path):
64
+ """Extract text from TXT file"""
65
+ with open(file_path, 'r', encoding='utf-8') as file:
66
+ return file.read()
67
+
68
+ def process_document(file):
69
+ """Process uploaded document and extract text"""
70
+ if file is None:
71
+ return ""
72
+
73
+ file_path = file.name
74
+ file_extension = os.path.splitext(file_path)[1].lower()
75
+
76
+ try:
77
+ if file_extension == '.pdf':
78
+ return extract_text_from_pdf(file_path)
79
+ elif file_extension == '.docx':
80
+ return extract_text_from_docx(file_path)
81
+ elif file_extension == '.txt':
82
+ return extract_text_from_txt(file_path)
83
+ else:
84
+ return "Unsupported file format. Please upload PDF, DOCX, or TXT files."
85
+ except Exception as e:
86
+ return f"Error processing file: {str(e)}"
87
+
88
+ # AI processing function with ZeroGPU
89
+ @spaces.GPU
90
+ def generate_content(text_input, file_input, task_type):
91
+ """Generate content using Llama 4 based on task type"""
92
+ # Get text content
93
+ if file_input is not None:
94
+ content = process_document(file_input)
95
+ else:
96
+ content = text_input
97
+
98
+ if not content:
99
+ return "Please provide text input or upload a file."
100
+
101
+ # Get the appropriate prompt
102
+ prompt_template = PROMPTS.get(task_type, PROMPTS["summaries"])
103
+ prompt = prompt_template.format(content=content)
104
+
105
+ try:
106
+ # Use chat completion which is more reliable
107
+ messages = [
108
+ {"role": "user", "content": prompt}
109
+ ]
110
+
111
+ response = client.chat_completion(
112
+ messages=messages,
113
+ max_tokens=2048,
114
+ temperature=0.7,
115
+ top_p=0.9
116
+ )
117
+
118
+ return response.choices[0].message.content
119
+
120
+ except Exception as e:
121
+ return f"Error generating content: {str(e)}"
122
+
123
+ # Main Gradio interface
124
+ with gr.Blocks(title="Document Study Assistant", theme=gr.themes.Soft()) as app:
125
+ gr.Markdown("# πŸ“š Document Study Assistant")
126
+ gr.Markdown("Upload documents or paste text to generate summaries, outlines, analysis, study guides, tables, and questions using Llama 4.")
127
+
128
+ with gr.Row():
129
+ with gr.Column(scale=1):
130
+ # Input section
131
+ gr.Markdown("### Input")
132
+ text_input = gr.Textbox(
133
+ label="Paste text here",
134
+ placeholder="Paste your text content here...",
135
+ lines=10,
136
+ max_lines=20
137
+ )
138
+
139
+ gr.Markdown("**OR**")
140
+
141
+ file_input = gr.File(
142
+ label="Upload Document",
143
+ file_types=[".pdf", ".docx", ".txt"],
144
+ file_count="single"
145
+ )
146
+
147
+ # Task selection
148
+ gr.Markdown("### Select Task")
149
+ task_type = gr.Radio(
150
+ choices=[
151
+ ("πŸ“ Summaries", "summaries"),
152
+ ("πŸ“‹ Outlines", "outlines"),
153
+ ("πŸ” Analysis", "analysis"),
154
+ ("πŸ“– Study Guides", "study_guides"),
155
+ ("πŸ“Š Tables", "tables"),
156
+ ("❓ Questions", "questions")
157
+ ],
158
+ value="summaries",
159
+ label="Choose what to generate"
160
+ )
161
+
162
+ generate_btn = gr.Button("πŸš€ Generate", variant="primary", size="lg")
163
+
164
+ with gr.Column(scale=1):
165
+ # Output section
166
+ gr.Markdown("### Output")
167
+ output = gr.Textbox(
168
+ label="Generated Content",
169
+ lines=25,
170
+ max_lines=50,
171
+ show_copy_button=True
172
+ )
173
+
174
+ # Connect the generate button to the function
175
+ generate_btn.click(
176
+ fn=generate_content,
177
+ inputs=[text_input, file_input, task_type],
178
+ outputs=output,
179
+ show_progress=True
180
+ )
181
+
182
+ if __name__ == "__main__":
183
+ app.launch()