-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflaskapp.py
More file actions
254 lines (205 loc) · 9.57 KB
/
Copy pathflaskapp.py
File metadata and controls
254 lines (205 loc) · 9.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
111
112
113
114
115
116
117
118
119
120
121
122
123
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
169
170
171
172
173
174
175
176
177
178
179
180
181
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import os
from flask import Flask, render_template, request, send_file, send_from_directory
import requests
from bs4 import BeautifulSoup
import networkx as nx
import matplotlib.pyplot as plt
from urllib.parse import urljoin, urlparse
from transformers import pipeline
from sentence_transformers import SentenceTransformer, util
import google.generativeai as genai
genai.configure(api_key='AIzaSyC1yN5KGES_TZgsK_ezQER7gL244vON2f8')
qa_pipeline = pipeline("question-answering", model="bert-large-uncased-whole-word-masking-finetuned-squad")
#qa_pipeline = pipeline("question-answering", model="distilbert-base-uncased-distilled-squad")
#qa_pipeline = pipeline("question-answering", model="deepset/roberta-large-squad2")
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
website_content = []
content_embeddings = []
def scrape_website(base_url: str, max_depth: int = 1):
"""Iteratively scrape a website to collect content and links up to a specified depth.Max Depth is 1 by default.Change it using max_depth parameter."""
visited_pages = set()
queue = [(base_url, 0)] # Queue stores tuples of (URL, current depth)
while queue:
url, current_depth = queue.pop(0)
if url in visited_pages or current_depth > max_depth:
continue
visited_pages.add(url)
try:
response = requests.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
except requests.exceptions.RequestException:
continue
page_text = soup.get_text(separator=" ").strip()
website_content.append({"url": url, "content": page_text})
embedding = embedding_model.encode(page_text)
content_embeddings.append(embedding)
for link in soup.find_all("a", href=True):
link_url = urljoin(base_url, link['href'])
if link_url.startswith(base_url) and link_url not in visited_pages:
queue.append((link_url, current_depth + 1))
def get_all_links(url):
"""Get all links from a single page."""
try:
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
links = set()
for a_tag in soup.find_all('a', href=True):
link = a_tag['href']
full_link = urljoin(url, link)
if urlparse(full_link).scheme in ['http', 'https']:
links.add(full_link)
return links
except Exception as e:
print(f"Error fetching links: {e}")
return set()
def visualize_links(main_url, links, output_image_path="website_structure.png"):
"""Visualize the structure of the website as a graph."""
G = nx.DiGraph()
G.add_node(main_url)
for link in links:
G.add_node(link)
G.add_edge(main_url, link)
pos = nx.spring_layout(G, k=0.5, iterations=50)
plt.figure(figsize=(12, 12))
nx.draw(G, pos, with_labels=True, node_size=3000, node_color="skyblue", font_size=10, font_weight='bold', arrows=True)
plt.title(f"Website Structure: {main_url}")
plt.savefig(output_image_path, format="PNG")
plt.close()
print(f"Visualization saved as {output_image_path}")
def generate_summary(transcript_text):
"""Summarize content using Google Gemini model."""
structured_prompt = ("""You are a website summarizer. Provide a summary of the following content within 300-500 words:\n\n""" f"Here is the content:\n\n{transcript_text}")
try:
model = genai.GenerativeModel("gemini-pro")
response = model.generate_content(structured_prompt)
return response.text
except Exception as e:
return f"Error generating summary: {e}"
def answer_question(question):
"""Answer questions based on scraped content using the QA model."""
question_embedding = embedding_model.encode(question)
similarities = util.cos_sim(question_embedding, content_embeddings)[0]
closest_idx = int(similarities.argmax())
content = website_content[closest_idx]["content"]
url = website_content[closest_idx]["url"]
answer = qa_pipeline(question=question, context=content)
return answer["answer"], answer["score"], url
def save_summary_to_file(summary, filename="static/website_summary.txt"):
"""Save the summary to a text file for download."""
try:
with open(filename, "w") as file:
file.write(summary)
return filename
except Exception as e:
return None
# def main():
# start_url = input("Enter the URL of the website to scan: ")
# print("Scraping website content...")
# scrape_website(start_url)
# print("Website content scraped successfully.")
# print("Fetching all links for structure visualization...")
# links = get_all_links(start_url)
# visualize_links(start_url, links)
# print("\nGenerating summaries for main page...")
# for page in website_content:
# if page['url'] == start_url:
# summary = generate_summary(page["content"])
# print(f"\nSummary for {page['url']}:\n{summary}")
# print("\nReady to answer questions.")
# while True:
# question = input("Ask a question (or type 'exit' to quit): ")
# if question.lower() == "exit":
# break
# answer, score, url = answer_question(question)
# print(f"Answer: {answer} (from: {url})\nConfidence Score: {score}\n")
# if __name__ == "__main__":
# main()
# Initialize Flask app
app = Flask(__name__)
# Folder configuration for file uploads and static files
app.config['UPLOAD_FOLDER'] = 'static'
app.config['ALLOWED_EXTENSIONS'] = {'txt'}
website_content = []
content_embeddings = []
summary = ""
@app.route('/')
def home():
"""Render the home page"""
return render_template('home.html')
# @app.route('/summarizer', methods=['GET', 'POST'])
# def my_summarizer():
# """Handle website URL input and summarize the content"""
# if request.method == 'POST':
# url = request.form['url']
# if url:
# global website_content, content_embeddings
# website_content.clear()
# content_embeddings.clear()
# # Scrape the website content
# scrape_website(url)
# # Get all links for visualization
# links = get_all_links(url)
# visualize_links(url, links)
# # Generate summary for the homepage
# for page in website_content:
# if page['url'] == url:
# summary = generate_summary(page["content"])
# # Save the summary to a text file
# save_summary_to_file(summary, os.path.join(app.config['UPLOAD_FOLDER'], 'website_summary.txt'))
# return render_template('summarizer.html', summary=summary, source_url=url, answer=None, score=None)
# return render_template('summarizer.html')
# @app.route('/summary', methods=['GET', 'POST'])
# def my_summary():
# """Render the summary page with Q&A functionality"""
# summary_text = ""
# answer = ""
# score = None
# if request.method == 'POST':
# question = request.form['question']
# if question:
# answer, score, url = answer_question(question)
# return render_template('summary.html', summary=summary_text, answer=answer, score=score, source_url=url)
# return render_template('summary.html', summary=summary_text, answer=answer, score=score)
@app.route('/summarizer', methods=['GET', 'POST'])
def my_summarizer():
"""Handle website URL input, summarize the content, and answer questions."""
global summary
answer = ""
score = None
source_url = None
if request.method == 'POST':
if 'url' in request.form:
# Process URL input and generate summary
url = request.form['url']
if url:
global website_content, content_embeddings
website_content.clear()
content_embeddings.clear()
# Scrape the website content
scrape_website(url)
# Get all links for visualization
links = get_all_links(url)
visualize_links(url, links)
# Generate summary for the homepage
for page in website_content:
if page['url'] == url:
summary = generate_summary(page["content"])
# Save the summary to a text file
save_summary_to_file(summary, os.path.join(app.config['UPLOAD_FOLDER'], 'static/website_summary.txt'))
source_url = url
elif 'question' in request.form:
# Process question input for Q&A functionality
question = request.form['question']
if question:
answer, score, source_url = answer_question(question)
return render_template('summarizer.html', summary=summary, source_url=source_url, answer=answer, score=score)
@app.route('/download_summary')
def download_summary():
"""Allow user to download the website summary"""
if summary:
save_summary_to_file(summary, 'static/website_summary.txt')
return send_file('static/website_summary.txt', as_attachment=True)
return "No summary available for download."
if __name__ == '__main__':
app.run(debug=True)