Shreyas094 commited on
Commit
e15b1c1
·
verified ·
1 Parent(s): 5ec38f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +250 -210
app.py CHANGED
@@ -8,237 +8,277 @@ import os
8
  from dotenv import load_dotenv
9
  import shutil
10
  import tempfile
 
11
  load_dotenv() # Load environment variables from .env file
 
12
  # Now replace the hard-coded token with the environment variable
13
  HUGGINGFACE_API_TOKEN = os.getenv("HUGGINGFACE_TOKEN")
 
14
  def clear_cache():
15
- try:
16
- # Clear Gradio cache
17
- cache_dir = tempfile.gettempdir()
18
- shutil.rmtree(os.path.join(cache_dir, "gradio"), ignore_errors=True)
19
- # Clear any custom cache you might have
20
- # For example, if you're caching PDF files or search results:
21
- if os.path.exists("output_summary.pdf"):
22
- os.remove("output_summary.pdf")
23
- # Add any other cache clearing operations here
24
- print("Cache cleared successfully.")
25
- return "Cache cleared successfully."
26
- except Exception as e:
27
- print(f"Error clearing cache: {e}")
28
- return f"Error clearing cache: {e}"
 
 
 
 
29
  _useragent_list = [
30
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
31
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
32
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59 Safari/537.36",
33
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59 Safari/537.36",
34
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36",
35
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36",
36
  ]
 
37
  # Function to extract visible text from HTML content of a webpage
38
  def extract_text_from_webpage(html):
39
- print("Extracting text from webpage...")
40
- soup = BeautifulSoup(html, 'html.parser')
41
- for script in soup(["script", "style"]):
42
- script.extract() # Remove scripts and styles
43
- text = soup.get_text()
44
- lines = (line.strip() for line in text.splitlines())
45
- chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
46
- text = '\n'.join(chunk for chunk in chunks if chunk)
47
- print(f"Extracted text length: {len(text)}")
48
- return text
 
49
  # Function to perform a Google search and retrieve results
50
  def google_search(term, num_results=5, lang="en", timeout=5, safe="active", ssl_verify=None):
51
- """Performs a Google search and returns the results."""
52
- print(f"Searching for term: {term}")
53
- escaped_term = urllib.parse.quote_plus(term)
54
- start = 0
55
- all_results = []
56
- max_chars_per_page = 8000 # Limit the number of characters from each webpage to stay under the token limit
57
- with requests.Session() as session:
58
- while start < num_results:
59
- print(f"Fetching search results starting from: {start}")
60
- try:
61
- # Choose a random user agent
62
- user_agent = random.choice(_useragent_list)
63
- headers = {
64
- 'User-Agent': user_agent
65
- }
66
- print(f"Using User-Agent: {headers['User-Agent']}")
67
- resp = session.get(
68
- url="https://www.google.com/search",
69
- headers=headers,
70
- params={
71
- "q": term,
72
- "num": num_results - start,
73
- "hl": lang,
74
- "start": start,
75
- "safe": safe,
76
- },
77
- timeout=timeout,
78
- verify=ssl_verify,
79
- )
80
- resp.raise_for_status()
81
- except requests.exceptions.RequestException as e:
82
- print(f"Error fetching search results: {e}")
83
- break
84
- soup = BeautifulSoup(resp.text, "html.parser")
85
- result_block = soup.find_all("div", attrs={"class": "g"})
86
- if not result_block:
87
- print("No more results found.")
88
- break
89
- for result in result_block:
90
- link = result.find("a", href=True)
91
- if link:
92
- link = link["href"]
93
- print(f"Found link: {link}")
94
- try:
95
- webpage = session.get(link, headers=headers, timeout=timeout)
96
- webpage.raise_for_status()
97
- visible_text = extract_text_from_webpage(webpage.text)
98
- if len(visible_text) > max_chars_per_page:
99
- visible_text = visible_text[:max_chars_per_page] + "..."
100
- all_results.append({"link": link, "text": visible_text})
101
- except requests.exceptions.RequestException as e:
102
- print(f"Error fetching or processing {link}: {e}")
103
- all_results.append({"link": link, "text": None})
104
- else:
105
- print("No link found in result.")
106
- all_results.append({"link": None, "text": None})
107
- start += len(result_block)
108
- print(f"Total results fetched: {len(all_results)}")
109
- return all_results
 
 
 
 
110
  # Function to format the prompt for the Hugging Face API
111
  def format_prompt(query, search_results, instructions):
112
- formatted_results = ""
113
- for result in search_results:
114
- link = result["link"]
115
- text = result["text"]
116
- if link:
117
- formatted_results += f"URL: {link}\nContent: {text}\n{'-' * 80}\n"
118
- else:
119
- formatted_results += "No link found.\n" + '-' * 80 + '\n'
120
- prompt = f"{instructions}User Query: {query}\n\nWeb Search Results:\n{formatted_results}\n\nAssistant:"
121
- return prompt
 
 
122
  # Function to generate text using Hugging Face API
123
  def generate_text(input_text, temperature=0.7, repetition_penalty=1.0, top_p=0.9):
124
- print("Generating text using Hugging Face API...")
125
- endpoint = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
126
- headers = {
127
- "Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}", # Use the environment variable
128
- "Content-Type": "application/json"
129
- }
130
- data = {
131
- "inputs": input_text,
132
- "parameters": {
133
- "max_new_tokens": 8000, # Adjust as needed
134
- "temperature": temperature,
135
- "repetition_penalty": repetition_penalty,
136
- "top_p": top_p
137
- }
138
- }
139
- try:
140
- response = requests.post(endpoint, headers=headers, json=data)
141
- response.raise_for_status()
142
- # Check if response is JSON
143
- try:
144
- json_data = response.json()
145
- except ValueError:
146
- print("Response is not JSON.")
147
- return None
148
- # Extract generated text from response JSON
149
- if isinstance(json_data, list):
150
- # Handle list response (if applicable for your use case)
151
- generated_text = json_data[0].get("generated_text") if json_data else None
152
- elif isinstance(json_data, dict):
153
- # Handle dictionary response
154
- generated_text = json_data.get("generated_text")
155
- else:
156
- print("Unexpected response format.")
157
- return None
158
- if generated_text is not None:
159
- print("Text generation complete using Hugging Face API.")
160
- print(f"Generated text: {generated_text}") # Debugging line
161
- return generated_text
162
- else:
163
- print("Generated text not found in response.")
164
- return None
165
- except requests.exceptions.RequestException as e:
166
- print(f"Error generating text using Hugging Face API: {e}")
167
- return None
 
 
 
 
 
 
168
  # Function to read and extract text from a PDF
169
  def read_pdf(file_obj):
170
- with fitz.open(file_obj.name) as document:
171
- text = ""
172
- for page_num in range(document.page_count):
173
- page = document.load_page(page_num)
174
- text += page.get_text()
175
- return text
 
176
  # Function to format the prompt with instructions for text generation
177
  def format_prompt_with_instructions(text, instructions):
178
- prompt = f"{instructions}{text}\n\nAssistant:"
179
- return prompt
 
180
  # Function to save text to a PDF
181
  def save_text_to_pdf(text, output_path):
182
- print(f"Saving text to PDF at {output_path}...")
183
- doc = fitz.open() # Create a new PDF document
184
- page = doc.new_page() # Create a new page
185
- # Set the page margins
186
- margin = 50 # 50 points margin
187
- page_width = page.rect.width
188
- page_height = page.rect.height
189
- text_width = page_width - 2 * margin
190
- text_height = page_height - 2 * margin
191
- # Define font size and line spacing
192
- font_size = 9
193
- line_spacing = 1 * font_size
194
- max_lines_per_page = int(text_height // line_spacing)
195
- # Load a built-in font
196
- font = "helv"
197
- # Split the text into lines
198
- lines = text.split("\n")
199
- current_line = 0
200
- for line in lines:
201
- if current_line >= max_lines_per_page:
202
- page = doc.new_page() # Add a new page
203
- current_line = 0
204
- rect = fitz.Rect(margin, margin + current_line * line_spacing, text_width, margin + (current_line + 1) * line_spacing)
205
- page.insert_textbox(rect, line, fontsize=font_size, fontname=font, align=fitz.TEXT_ALIGN_LEFT)
206
- current_line += 1
207
- doc.save(output_path)
208
- print(f"Text saved to PDF at {output_path}.")
 
 
 
 
 
 
 
 
209
  # Function to handle user queries
210
  def handle_query(query, is_read_pdf, instructions, pdf_file=None):
211
- print("Handling user query...")
212
- max_chars_per_chunk = 1000 # Adjust this value as needed to control chunk size
213
- if is_read_pdf and pdf_file:
214
- pdf_text = read_pdf(pdf_file)
215
- text_chunks = [pdf_text[i:i+max_chars_per_chunk] for i in range(0, len(pdf_text), max_chars_per_chunk)]
216
- else:
217
- search_results = google_search(query)
218
- text_chunks = []
219
- for result in search_results:
220
- if result["text"]:
221
- text_chunks.extend([result["text"][i:i+max_chars_per_chunk] for i in range(0, len(result["text"]), max_chars_per_chunk)])
222
- summaries = []
223
- for chunk in text_chunks:
224
- formatted_prompt = format_prompt_with_instructions(chunk, instructions)
225
- summary = generate_text(formatted_prompt)
226
- if summary:
227
- summaries.append(summary)
228
- combined_summary = " ".join(summaries)
229
- save_text_to_pdf(combined_summary, "output_summary.pdf")
230
- return combined_summary
 
 
 
 
231
  def run_app():
232
- with gr.Blocks() as demo:
233
- gr.Markdown("# Web and PDF Summarizer")
234
- query = gr.Textbox(label="Enter your query", placeholder="Enter query here")
235
- pdf_file = gr.File(label="Upload PDF", file_types=[".pdf"])
236
- is_read_pdf = gr.Checkbox(label="Read PDF", value=False)
237
- instructions = gr.Textbox(label="Enter instructions", placeholder="Enter instructions here")
238
- output = gr.Textbox(label="Summary")
239
- clear_cache_btn = gr.Button("Clear Cache")
240
- clear_cache_btn.click(fn=clear_cache, outputs=output)
241
- generate_btn = gr.Button("Generate Summary")
242
- generate_btn.click(fn=handle_query, inputs=[query, is_read_pdf, instructions, pdf_file], outputs=output)
243
- demo.launch()
 
 
 
 
 
244
  run_app()
 
8
  from dotenv import load_dotenv
9
  import shutil
10
  import tempfile
11
+
12
  load_dotenv() # Load environment variables from .env file
13
+
14
  # Now replace the hard-coded token with the environment variable
15
  HUGGINGFACE_API_TOKEN = os.getenv("HUGGINGFACE_TOKEN")
16
+
17
  def clear_cache():
18
+ try:
19
+ # Clear Gradio cache
20
+ cache_dir = tempfile.gettempdir()
21
+ shutil.rmtree(os.path.join(cache_dir, "gradio"), ignore_errors=True)
22
+
23
+ # Clear any custom cache you might have
24
+ # For example, if you're caching PDF files or search results:
25
+ if os.path.exists("output_summary.pdf"):
26
+ os.remove("output_summary.pdf")
27
+
28
+ # Add any other cache clearing operations here
29
+
30
+ print("Cache cleared successfully.")
31
+ return "Cache cleared successfully."
32
+ except Exception as e:
33
+ print(f"Error clearing cache: {e}")
34
+ return f"Error clearing cache: {e}"
35
+
36
  _useragent_list = [
37
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
38
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
39
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59 Safari/537.36",
40
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59 Safari/537.36",
41
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36",
42
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36",
43
  ]
44
+
45
  # Function to extract visible text from HTML content of a webpage
46
  def extract_text_from_webpage(html):
47
+ print("Extracting text from webpage...")
48
+ soup = BeautifulSoup(html, 'html.parser')
49
+ for script in soup(["script", "style"]):
50
+ script.extract() # Remove scripts and styles
51
+ text = soup.get_text()
52
+ lines = (line.strip() for line in text.splitlines())
53
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
54
+ text = '\n'.join(chunk for chunk in chunks if chunk)
55
+ print(f"Extracted text length: {len(text)}")
56
+ return text
57
+
58
  # Function to perform a Google search and retrieve results
59
  def google_search(term, num_results=5, lang="en", timeout=5, safe="active", ssl_verify=None):
60
+ """Performs a Google search and returns the results."""
61
+ print(f"Searching for term: {term}")
62
+ escaped_term = urllib.parse.quote_plus(term)
63
+ start = 0
64
+ all_results = []
65
+ max_chars_per_page = 8000 # Limit the number of characters from each webpage to stay under the token limit
66
+
67
+ with requests.Session() as session:
68
+ while start < num_results:
69
+ print(f"Fetching search results starting from: {start}")
70
+ try:
71
+ # Choose a random user agent
72
+ user_agent = random.choice(_useragent_list)
73
+ headers = {
74
+ 'User-Agent': user_agent
75
+ }
76
+ print(f"Using User-Agent: {headers['User-Agent']}")
77
+
78
+ resp = session.get(
79
+ url="https://www.google.com/search",
80
+ headers=headers,
81
+ params={
82
+ "q": term,
83
+ "num": num_results - start,
84
+ "hl": lang,
85
+ "start": start,
86
+ "safe": safe,
87
+ },
88
+ timeout=timeout,
89
+ verify=ssl_verify,
90
+ )
91
+ resp.raise_for_status()
92
+ except requests.exceptions.RequestException as e:
93
+ print(f"Error fetching search results: {e}")
94
+ break
95
+
96
+ soup = BeautifulSoup(resp.text, "html.parser")
97
+ result_block = soup.find_all("div", attrs={"class": "g"})
98
+ if not result_block:
99
+ print("No more results found.")
100
+ break
101
+ for result in result_block:
102
+ link = result.find("a", href=True)
103
+ if link:
104
+ link = link["href"]
105
+ print(f"Found link: {link}")
106
+ try:
107
+ webpage = session.get(link, headers=headers, timeout=timeout)
108
+ webpage.raise_for_status()
109
+ visible_text = extract_text_from_webpage(webpage.text)
110
+ if len(visible_text) > max_chars_per_page:
111
+ visible_text = visible_text[:max_chars_per_page] + "..."
112
+ all_results.append({"link": link, "text": visible_text})
113
+ except requests.exceptions.RequestException as e:
114
+ print(f"Error fetching or processing {link}: {e}")
115
+ all_results.append({"link": link, "text": None})
116
+ else:
117
+ print("No link found in result.")
118
+ all_results.append({"link": None, "text": None})
119
+ start += len(result_block)
120
+ print(f"Total results fetched: {len(all_results)}")
121
+ return all_results
122
+
123
  # Function to format the prompt for the Hugging Face API
124
  def format_prompt(query, search_results, instructions):
125
+ formatted_results = ""
126
+ for result in search_results:
127
+ link = result["link"]
128
+ text = result["text"]
129
+ if link:
130
+ formatted_results += f"URL: {link}\nContent: {text}\n{'-' * 80}\n"
131
+ else:
132
+ formatted_results += "No link found.\n" + '-' * 80 + '\n'
133
+
134
+ prompt = f"{instructions}User Query: {query}\n\nWeb Search Results:\n{formatted_results}\n\nAssistant:"
135
+ return prompt
136
+
137
  # Function to generate text using Hugging Face API
138
  def generate_text(input_text, temperature=0.7, repetition_penalty=1.0, top_p=0.9):
139
+ print("Generating text using Hugging Face API...")
140
+ endpoint = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
141
+ headers = {
142
+ "Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}", # Use the environment variable
143
+ "Content-Type": "application/json"
144
+ }
145
+ data = {
146
+ "inputs": input_text,
147
+ "parameters": {
148
+ "max_new_tokens": 8000, # Adjust as needed
149
+ "temperature": temperature,
150
+ "repetition_penalty": repetition_penalty,
151
+ "top_p": top_p
152
+ }
153
+ }
154
+
155
+ try:
156
+ response = requests.post(endpoint, headers=headers, json=data)
157
+ response.raise_for_status()
158
+
159
+ # Check if response is JSON
160
+ try:
161
+ json_data = response.json()
162
+ except ValueError:
163
+ print("Response is not JSON.")
164
+ return None
165
+
166
+ # Extract generated text from response JSON
167
+ if isinstance(json_data, list):
168
+ # Handle list response (if applicable for your use case)
169
+ generated_text = json_data[0].get("generated_text") if json_data else None
170
+ elif isinstance(json_data, dict):
171
+ # Handle dictionary response
172
+ generated_text = json_data.get("generated_text")
173
+ else:
174
+ print("Unexpected response format.")
175
+ return None
176
+
177
+ if generated_text is not None:
178
+ print("Text generation complete using Hugging Face API.")
179
+ print(f"Generated text: {generated_text}") # Debugging line
180
+ return generated_text
181
+ else:
182
+ print("Generated text not found in response.")
183
+ return None
184
+
185
+ except requests.exceptions.RequestException as e:
186
+ print(f"Error generating text using Hugging Face API: {e}")
187
+ return None
188
+
189
  # Function to read and extract text from a PDF
190
  def read_pdf(file_obj):
191
+ with fitz.open(file_obj.name) as document:
192
+ text = ""
193
+ for page_num in range(document.page_count):
194
+ page = document.load_page(page_num)
195
+ text += page.get_text()
196
+ return text
197
+
198
  # Function to format the prompt with instructions for text generation
199
  def format_prompt_with_instructions(text, instructions):
200
+ prompt = f"{instructions}{text}\n\nAssistant:"
201
+ return prompt
202
+
203
  # Function to save text to a PDF
204
  def save_text_to_pdf(text, output_path):
205
+ print(f"Saving text to PDF at {output_path}...")
206
+ doc = fitz.open() # Create a new PDF document
207
+ page = doc.new_page() # Create a new page
208
+
209
+ # Set the page margins
210
+ margin = 50 # 50 points margin
211
+ page_width = page.rect.width
212
+ page_height = page.rect.height
213
+ text_width = page_width - 2 * margin
214
+ text_height = page_height - 2 * margin
215
+
216
+ # Define font size and line spacing
217
+ font_size = 9
218
+ line_spacing = 1 * font_size
219
+ max_lines_per_page = int(text_height // line_spacing)
220
+
221
+ # Load a built-in font
222
+ font = "helv"
223
+
224
+ # Split the text into lines
225
+ lines = text.split("\n")
226
+
227
+ current_line = 0
228
+ for line in lines:
229
+ if current_line >= max_lines_per_page:
230
+ page = doc.new_page() # Add a new page
231
+ current_line = 0
232
+
233
+ rect = fitz.Rect(margin, margin + current_line * line_spacing, text_width, margin + (current_line + 1) * line_spacing)
234
+ page.insert_textbox(rect, line, fontsize=font_size, fontname=font, align=fitz.TEXT_ALIGN_LEFT)
235
+ current_line += 1
236
+
237
+ doc.save(output_path)
238
+ print(f"Text saved to PDF at {output_path}.")
239
+
240
  # Function to handle user queries
241
  def handle_query(query, is_read_pdf, instructions, pdf_file=None):
242
+ print("Handling user query...")
243
+ max_chars_per_chunk = 1000 # Adjust this value as needed to control chunk size
244
+
245
+ if is_read_pdf and pdf_file:
246
+ pdf_text = read_pdf(pdf_file)
247
+ text_chunks = [pdf_text[i:i+max_chars_per_chunk] for i in range(0, len(pdf_text), max_chars_per_chunk)]
248
+ else:
249
+ search_results = google_search(query)
250
+ text_chunks = []
251
+ for result in search_results:
252
+ if result["text"]:
253
+ text_chunks.extend([result["text"][i:i+max_chars_per_chunk] for i in range(0, len(result["text"]), max_chars_per_chunk)])
254
+
255
+ summaries = []
256
+ for chunk in text_chunks:
257
+ formatted_prompt = format_prompt_with_instructions(chunk, instructions)
258
+ summary = generate_text(formatted_prompt)
259
+ if summary:
260
+ summaries.append(summary)
261
+
262
+ combined_summary = " ".join(summaries)
263
+ save_text_to_pdf(combined_summary, "output_summary.pdf")
264
+ return combined_summary
265
+
266
  def run_app():
267
+ with gr.Blocks() as demo:
268
+ gr.Markdown("# Web and PDF Summarizer")
269
+
270
+ query = gr.Textbox(label="Enter your query", placeholder="Enter query here")
271
+ pdf_file = gr.File(label="Upload PDF", file_types=[".pdf"])
272
+ is_read_pdf = gr.Checkbox(label="Read PDF", value=False)
273
+ instructions = gr.Textbox(label="Enter instructions", placeholder="Enter instructions here")
274
+ output = gr.Textbox(label="Summary")
275
+
276
+ clear_cache_btn = gr.Button("Clear Cache")
277
+ clear_cache_btn.click(fn=clear_cache, outputs=output)
278
+
279
+ generate_btn = gr.Button("Generate Summary")
280
+ generate_btn.click(fn=handle_query, inputs=[query, is_read_pdf, instructions, pdf_file], outputs=output)
281
+
282
+ demo.launch()
283
+
284
  run_app()