Spaces:
Build error
Build error
Update app.py
Browse files
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 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
_useragent_list = [
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
]
|
|
|
|
| 37 |
# Function to extract visible text from HTML content of a webpage
|
| 38 |
def extract_text_from_webpage(html):
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
| 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 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
# Function to format the prompt for the Hugging Face API
|
| 111 |
def format_prompt(query, search_results, instructions):
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
| 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 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
# Function to read and extract text from a PDF
|
| 169 |
def read_pdf(file_obj):
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
|
|
|
| 176 |
# Function to format the prompt with instructions for text generation
|
| 177 |
def format_prompt_with_instructions(text, instructions):
|
| 178 |
-
|
| 179 |
-
|
|
|
|
| 180 |
# Function to save text to a PDF
|
| 181 |
def save_text_to_pdf(text, output_path):
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
# Function to handle user queries
|
| 210 |
def handle_query(query, is_read_pdf, instructions, pdf_file=None):
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
def run_app():
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|