SlouchyBuffalo commited on
Commit
8553eef
Β·
verified Β·
1 Parent(s): afc5fc7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +162 -0
app.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import spaces
3
+ import PyPDF2
4
+ import docx
5
+ import io
6
+ import requests
7
+ import os
8
+ from typing import Optional
9
+
10
+ # Prompts for each operation (keeping same as before)
11
+ PROMPTS = {
12
+ "Summary": """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. If the document includes specific sections (e.g., abstract, conclusion), prioritize those for key insights.""",
13
+
14
+ "Outline": """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. If the document has a table of contents or headings, align the outline with its structure.""",
15
+
16
+ "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.""",
17
+
18
+ "Study Guide": """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, drawing directly from the document's content.""",
19
+
20
+ "Table": """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. If applicable, use data or examples from the document to enhance clarity.""",
21
+
22
+ "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. Provide a brief introduction (50 words) explaining the questions' purpose, referencing the document's content."""
23
+ }
24
+
25
+ def extract_text_from_file(file) -> str:
26
+ """Extract text from uploaded files"""
27
+ if file is None:
28
+ return ""
29
+
30
+ file_path = file.name
31
+ text = ""
32
+
33
+ try:
34
+ if file_path.endswith('.pdf'):
35
+ with open(file_path, 'rb') as f:
36
+ reader = PyPDF2.PdfReader(f)
37
+ for page in reader.pages:
38
+ text += page.extract_text() + "\n"
39
+
40
+ elif file_path.endswith('.docx'):
41
+ doc = docx.Document(file_path)
42
+ for paragraph in doc.paragraphs:
43
+ text += paragraph.text + "\n"
44
+
45
+ elif file_path.endswith('.txt'):
46
+ with open(file_path, 'r', encoding='utf-8') as f:
47
+ text = f.read()
48
+ except Exception as e:
49
+ return f"Error reading file: {str(e)}"
50
+
51
+ return text
52
+
53
+ def call_llama_inference(prompt: str, max_tokens: int = 2000) -> str:
54
+ """Call HuggingFace Inference API for Llama 3.3 70B"""
55
+ api_token = os.getenv('HF_TOKEN')
56
+
57
+ if not api_token:
58
+ return "Error: HuggingFace token not found. Please set the HF_TOKEN secret in your Space settings."
59
+
60
+ # Using HuggingFace's hosted inference endpoint for Cerebras/Llama-3.3-70B
61
+ api_url = "https://api-inference.huggingface.co/models/Cerebras/Llama-3.3-70B-Instruct"
62
+
63
+ headers = {
64
+ "Authorization": f"Bearer {api_token}",
65
+ "Content-Type": "application/json"
66
+ }
67
+
68
+ payload = {
69
+ "inputs": prompt,
70
+ "parameters": {
71
+ "max_new_tokens": max_tokens,
72
+ "temperature": 0.1,
73
+ "do_sample": True,
74
+ "return_full_text": False
75
+ }
76
+ }
77
+
78
+ try:
79
+ response = requests.post(api_url, headers=headers, json=payload, timeout=120)
80
+
81
+ if response.status_code == 200:
82
+ result = response.json()
83
+ if isinstance(result, list) and len(result) > 0:
84
+ return result[0].get('generated_text', 'No response generated')
85
+ else:
86
+ return str(result)
87
+ else:
88
+ return f"Error: API request failed with status {response.status_code}: {response.text}"
89
+
90
+ except Exception as e:
91
+ return f"Error calling HuggingFace API: {str(e)}"
92
+
93
+ @spaces.GPU
94
+ def process_document(document, operation_type, text_input):
95
+ """Main processing function"""
96
+ # Extract text from file or use text input
97
+ if document is not None:
98
+ text = extract_text_from_file(document)
99
+ else:
100
+ text = text_input
101
+
102
+ if not text.strip():
103
+ return "Please provide either a document or text input."
104
+
105
+ # Get the appropriate prompt
106
+ prompt = PROMPTS.get(operation_type, "")
107
+
108
+ # Combine prompt with document text
109
+ full_prompt = f"{prompt}\n\nDocument content:\n{text}"
110
+
111
+ # Call HuggingFace Inference API with Cerebras Llama
112
+ result = call_llama_inference(full_prompt)
113
+
114
+ return result
115
+
116
+ # Create the Gradio interface
117
+ with gr.Blocks(title="Study Assistant", theme=gr.themes.Soft()) as demo:
118
+ gr.Markdown("# πŸ“š Study Assistant - Document Analysis Tool")
119
+ gr.Markdown("Upload a document or paste text, then select the type of analysis you want to perform.")
120
+
121
+ with gr.Row():
122
+ with gr.Column():
123
+ document = gr.File(
124
+ label="Upload Document",
125
+ file_types=[".pdf", ".docx", ".txt"],
126
+ file_count="single"
127
+ )
128
+ text_input = gr.Textbox(
129
+ label="Or paste text directly",
130
+ lines=5,
131
+ placeholder="Paste your text here if you don't want to upload a file..."
132
+ )
133
+
134
+ with gr.Column():
135
+ operation_type = gr.Dropdown(
136
+ choices=["Summary", "Outline", "Analysis", "Study Guide", "Table", "Questions"],
137
+ label="Select Operation",
138
+ value="Summary"
139
+ )
140
+ process_btn = gr.Button("Process Document", variant="primary", size="lg")
141
+
142
+ output = gr.Textbox(
143
+ label="Output",
144
+ lines=20,
145
+ show_copy_button=True
146
+ )
147
+
148
+ gr.Markdown("---")
149
+ gr.Markdown("### Tips:")
150
+ gr.Markdown("- Supported formats: PDF, DOCX, TXT")
151
+ gr.Markdown("- Maximum file size: 200MB")
152
+ gr.Markdown("- Text can be pasted directly if you don't have a file")
153
+ gr.Markdown("- Powered by Cerebras Llama-3.3-70B through HuggingFace")
154
+
155
+ process_btn.click(
156
+ fn=process_document,
157
+ inputs=[document, operation_type, text_input],
158
+ outputs=output
159
+ )
160
+
161
+ if __name__ == "__main__":
162
+ demo.launch()