Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
293 lines (253 loc) · 11 KB
/
Copy pathapp.py
File metadata and controls
293 lines (253 loc) · 11 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import os
import io
import re
import requests
import fitz # PyMuPDF
from dotenv import load_dotenv
from flask import Flask, render_template, request, send_file, jsonify
from summarizer import summarize_text, SummaryType
from fpdf import FPDF
import docx
from werkzeug.utils import secure_filename
# Load env variables from .env
load_dotenv()
app = Flask(__name__)
# Load key from env, falling back to a secure default if undefined
app.secret_key = os.getenv("FLASK_SECRET_KEY", "prod-fallback-secure-key-928471")
ALLOWED_EXTENSIONS = {"txt", "pdf", "docx"}
def allowed_file(filename):
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
def clean_text_for_pdf(text):
# Remove HTML tags (e.g., <b>, </b>, <br>)
text_clean = re.sub(r'<[^>]+>', '', text)
# Replace common characters that might be problematic or have basic equivalents
replacements = {
'📝': '',
'•': '-',
'’': "'",
'‘': "'",
'”': '"',
'“': '"',
'—': '-',
'–': '-',
}
for orig, rep in replacements.items():
text_clean = text_clean.replace(orig, rep)
# Safe encoding to latin-1 (ignore any un-encodable characters)
return text_clean.encode('latin-1', errors='ignore').decode('latin-1')
@app.route("/debug-dns")
def debug_dns():
import socket
import subprocess
results = {}
# 1. Try socket.gethostbyname for Hugging Face
try:
results["gethostbyname_hf"] = socket.gethostbyname("router.huggingface.co")
except Exception as e:
results["gethostbyname_hf"] = f"Error: {e}"
# 2. Try socket.gethostbyname for Google
try:
results["gethostbyname_google"] = socket.gethostbyname("google.com")
except Exception as e:
results["gethostbyname_google"] = f"Error: {e}"
# 3. Try running nslookup for Hugging Face
try:
res = subprocess.run(["nslookup", "router.huggingface.co"], capture_output=True, text=True, timeout=5)
results["nslookup_hf"] = f"STDOUT:\n{res.stdout}\nSTDERR:\n{res.stderr}"
except Exception as e:
results["nslookup_hf"] = f"Error: {e}"
# 4. Try running curl to Hugging Face status or API URL
try:
res = subprocess.run(["curl", "-I", "https://router.huggingface.co"], capture_output=True, text=True, timeout=5)
results["curl_hf"] = f"STDOUT:\n{res.stdout}\nSTDERR:\n{res.stderr}"
except Exception as e:
results["curl_hf"] = f"Error: {e}"
return results
@app.route("/")
def home():
return render_template("index.html")
@app.route("/summarize", methods=["GET", "POST"])
def summarize():
summary = ""
input_text = ""
selected_summary_type = "Paragraph"
selected_language = "English"
selected_length = "Medium"
if request.method == "POST":
input_text = request.form.get("noteText", "")
uploaded_file = request.files.get("file")
selected_summary_type = request.form.get("summaryType", "Paragraph")
selected_language = request.form.get("language", "English")
selected_length = request.form.get("length", "Medium")
# Handle file upload validation and parsing
if uploaded_file and uploaded_file.filename != "":
if not allowed_file(uploaded_file.filename):
input_text = "Error: Unsupported file format. Please upload only .txt, .docx, or .pdf files."
else:
filename = secure_filename(uploaded_file.filename)
if filename.endswith(".docx"):
try:
doc = docx.Document(uploaded_file)
input_text = "\n".join([para.text for para in doc.paragraphs])
except Exception as e:
input_text = f"Error reading DOCX: {e}"
elif filename.endswith(".txt"):
try:
input_text = uploaded_file.read().decode("utf-8")
except Exception as e:
input_text = f"Error reading TXT: {e}"
elif filename.endswith(".pdf"):
try:
pdf_data = uploaded_file.read()
pdf_doc = fitz.open(stream=pdf_data, filetype="pdf")
pdf_text_parts = []
for page in pdf_doc:
page_text = page.get_text()
if page_text:
pdf_text_parts.append(page_text)
input_text = "\n".join(pdf_text_parts)
except Exception as e:
input_text = f"Error reading PDF: {e}"
length_map = {
"Short": (30, 80),
"Medium": (80, 150),
"Long": (150, 300)
}
min_len, max_len = length_map.get(selected_length, (80, 150))
# Check if input text is valid and has no parser errors
if input_text.strip() and not input_text.startswith("Error"):
# Map selected language to Google Translate codes
lang_map = {
"Tamil": "ta",
"Hindi": "hi"
}
target_lang = lang_map.get(selected_language)
processing_text = input_text
# If target language is Hindi or Tamil, translate the input text to English first
if target_lang:
processing_text = translate_text(input_text, src="auto", dest="en")
# Summarize in English
summary_en = summarize_text(processing_text, min_len, max_len, selected_summary_type)
# If target language is Hindi or Tamil, translate the English summary back
if target_lang and not summary_en.startswith("⚠️"):
summary = translate_text(summary_en, src="en", dest=target_lang)
else:
summary = summary_en
else:
summary = f"⚠️ Error: {input_text or 'No text or file provided.'}"
return jsonify({
"success": not summary.startswith("⚠️"),
"summary": summary,
"input_text": input_text,
"key_topics": extract_key_topics(processing_text) if not summary.startswith("⚠️") else []
})
return render_template("summarize.html",
summary=summary,
input_text=input_text,
selected_summary_type=selected_summary_type,
selected_language=selected_language,
selected_length=selected_length)
@app.route("/download_pdf", methods=["POST"])
def download_pdf():
summary_text = request.form.get("summary_text", "No summary available.")
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
for line in summary_text.split('<br>'):
cleaned_line = clean_text_for_pdf(line).strip()
if cleaned_line:
pdf.multi_cell(0, 10, cleaned_line, 0, 'L')
# Output to memory string, encode to latin-1 bytes
pdf_string = pdf.output(dest='S')
pdf_bytes = pdf_string.encode('latin-1')
# Send the memory stream directly
return send_file(
io.BytesIO(pdf_bytes),
mimetype='application/pdf',
as_attachment=True,
download_name="summary.pdf"
)
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/contact")
def contact():
return render_template("contact.html")
@app.route("/privacy")
def privacy():
return render_template("privacy.html")
def translate_text(text, src="auto", dest="en"):
if not text.strip():
return ""
# Split by paragraphs or chunks of ~2000 chars
max_chunk = 2000
chunks = []
current_chunk = []
current_len = 0
for line in text.split('\n'):
if current_len + len(line) + 1 > max_chunk:
chunks.append('\n'.join(current_chunk))
current_chunk = [line]
current_len = len(line)
else:
current_chunk.append(line)
current_len += len(line) + 1
if current_chunk:
chunks.append('\n'.join(current_chunk))
translated_chunks = []
for chunk in chunks:
if not chunk.strip():
continue
try:
url = "https://translate.googleapis.com/translate_a/single"
params = {
"client": "gtx",
"sl": src,
"tl": dest,
"dt": "t",
"q": chunk
}
r = requests.get(url, params=params, timeout=10)
r.raise_for_status()
res = r.json()
translated_chunk = "".join([segment[0] for segment in res[0] if segment[0]])
translated_chunks.append(translated_chunk)
except Exception as e:
# Fallback to original chunk if translation fails
translated_chunks.append(chunk)
return '\n'.join(translated_chunks)
def extract_key_topics(text, max_topics=5):
# Standard list of common English stopwords to ignore
stopwords = {
"i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours",
"yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers",
"herself", "it", "its", "itself", "they", "them", "their", "theirs", "themselves",
"what", "which", "who", "whom", "this", "that", "these", "those", "am", "is", "are",
"was", "were", "be", "been", "being", "have", "has", "had", "having", "do", "does",
"did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until",
"while", "of", "at", "by", "for", "with", "about", "against", "between", "into",
"through", "during", "before", "after", "above", "below", "to", "from", "up", "down",
"in", "out", "on", "off", "over", "under", "again", "further", "then", "once", "here",
"there", "when", "where", "why", "how", "all", "any", "both", "each", "few", "more",
"most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so",
"than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now",
"would", "could", "also", "using", "use", "make", "get", "like", "one", "two", "new"
}
# Clean text: remove non-alphabetic characters
cleaned = re.sub(r'[^a-zA-Z\s]', '', text).lower()
words = cleaned.split()
# Filter words (longer than 3 chars, not in stopwords)
filtered = [w for w in words if len(w) > 3 and w not in stopwords]
# Count frequencies
freq = {}
for w in filtered:
freq[w] = freq.get(w, 0) + 1
# Sort by frequency and then by length
sorted_words = sorted(freq.items(), key=lambda item: (item[1], len(item[0])), reverse=True)
# Return top N keywords capitalized
topics = [item[0].capitalize() for item in sorted_words[:max_topics]]
return topics
if __name__ == "__main__":
# Render binds dynamically to the PORT environment variable
port = int(os.getenv("PORT", 5000))
app.run(host="0.0.0.0", port=port, debug=False)