-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3779 lines (3168 loc) · 163 KB
/
main.py
File metadata and controls
3779 lines (3168 loc) · 163 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import markdown
from flask import Flask, render_template, request, redirect, url_for, jsonify, session, flash
from werkzeug.security import generate_password_hash, check_password_hash
import os
import fitz # PyMuPDF for text-based PDFs
import pytesseract # OCR for images
import requests # To call the AI API
from PIL import Image
import sqlite3
from deep_translator import GoogleTranslator
from translate import Translator
from flask_wtf.csrf import CSRFProtect, generate_csrf
import re
import datetime
from datetime import timedelta
import base64
import numpy as np # For table extraction
import pandas as pd # For table handling
from sklearn.feature_extraction.text import TfidfVectorizer # For topic extraction
import spacy # For NLP tasks
import io # For in-memory file handling
import uuid # For generating unique IDs
from tabulate import tabulate
# Import prompts from the prompts module
from prompts import (
SUMMARY_PROMPT,
QUESTIONS_PROMPT,
CHAT_SYSTEM_PROMPT,
CONTEXT_PROMPT,
FALLBACK_QUESTIONS,
COMMON_RESPONSE_PREFIXES,
DOCUMENT_CATEGORIES,
SENTIMENT_WORDS,
ENTITY_TYPE_MAP,
CITATION_PATTERNS
)
import zlib # For compression
# Load environment variables from .env file if it exists
try:
from dotenv import load_dotenv
load_dotenv()
print("Environment variables loaded from .env file")
except ImportError:
print("python-dotenv not installed. Environment variables not loaded from .env file.")
except Exception as e:
print(f"Error loading .env file: {str(e)}")
try:
nlp = spacy.load("en_core_web_sm")
print("Successfully loaded spaCy model")
except Exception as e:
print(f"Could not load spaCy model: {str(e)}")
print("Named entity recognition and advanced NLP features will be limited")
print("To install the model, run: python -m spacy download en_core_web_sm")
nlp = None
# Add a helper function to check if NLP is available
def is_nlp_available():
"""Check if NLP functionality is available (spaCy is loaded)"""
return nlp is not None
app = Flask(__name__)
# Use environment variable for secret key if available, otherwise use a fixed one
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "JaiWn5ackErSta6UxabrAPhewrumeJUhEsWeGe4pE3uthAspujefr8c")
app.config["UPLOAD_FOLDER"] = "uploads"
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7) # Session lasts 7 days
app.config['WTF_CSRF_ENABLED'] = True
# Use environment variable for CSRF secret key if available, otherwise use a fixed one
app.config['WTF_CSRF_SECRET_KEY'] = os.environ.get("FLASK_CSRF_SECRET_KEY", "pudr2swA8rUcRuThASAxUcRap5ath7sTabruThEsWuDr6he7r9phu")
app.config['SESSION_COOKIE_SECURE'] = os.environ.get("SESSION_COOKIE_SECURE", "False").lower() == "true"
app.config['SESSION_COOKIE_HTTPONLY'] = True # Prevent JavaScript access to session cookie
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' # CSRF protection
# Add file-based session configuration to prevent cookie size issues
os.makedirs('flask_session', exist_ok=True) # Create directory for session files
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_FILE_DIR'] = 'flask_session'
app.config['SESSION_PERMANENT'] = True
app.config['SESSION_USE_SIGNER'] = True
# Initialize the Flask-Session extension
from flask_session import Session
sess = Session(app)
csrf = CSRFProtect(app)
# Exempt certain routes from CSRF protection
csrf.exempt('/translate_content')
csrf.exempt('/translate_summary')
csrf.exempt('/translate_questions')
csrf.exempt('/debug_translate')
csrf.exempt('/chat') # Exempt chat route from CSRF protection since it's an API endpoint
# Ensure upload folder exists
os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)
# Password validation regex
PASSWORD_REGEX = re.compile(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$')
# --- Database Setup ---
def init_db():
conn = sqlite3.connect("users.db")
cursor = conn.cursor()
# Create users table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
remember_token TEXT
)
""")
# Check if remember_token column exists, add it if it doesn't
cursor.execute("PRAGMA table_info(users)")
columns = [column[1] for column in cursor.fetchall()]
if "remember_token" not in columns:
cursor.execute("ALTER TABLE users ADD COLUMN remember_token TEXT")
print("Added remember_token column to users table")
conn.commit()
conn.close()
init_db()
# --- Helper Functions ---
def is_valid_email(email):
email_regex = r'^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$'
return re.match(email_regex, email) is not None
def is_valid_password(password):
return PASSWORD_REGEX.match(password) is not None
def generate_remember_token():
return os.urandom(24).hex()
def compress_data(data):
"""Compress text data to save session space, using only base64 encoding"""
if not data:
return None
try:
# Just use base64 encoding without compression
if isinstance(data, str):
data_bytes = data.encode("utf-8")
encoded_data = base64.b64encode(data_bytes).decode("utf-8")
return encoded_data
else:
# If not a string, return as is
print(f"Warning: Non-string data passed to compress_data: {type(data)}")
return data
except Exception as e:
print(f"Error compressing data: {str(e)}")
# Return original data on error
return data
def decompress_data(data):
"""Decompress text data from session, using only base64 decoding"""
if not data:
return ""
try:
# Just use base64 decoding without decompression
if isinstance(data, str):
try:
decoded_data = base64.b64decode(data.encode("utf-8")).decode("utf-8")
return decoded_data
except:
# If decoding fails, it might not be encoded data
print("Warning: Could not decode data, returning as is")
return data
else:
# If not a string, return as is
print(f"Warning: Non-string data passed to decompress_data: {type(data)}")
return str(data)
except Exception as e:
print(f"Error decompressing data: {str(e)}")
# Return string representation on error
return str(data)
def get_from_session(key, default=""):
"""Get data from session with automatic decompression"""
try:
if key not in session:
return default
value = session.get(key, default)
if value is None:
return default
# If the value is a string and looks compressed, try to decompress it
if isinstance(value, str) and value.startswith("__COMPRESSED__"):
try:
compressed_data = base64.b64decode(value[14:])
return zlib.decompress(compressed_data).decode('utf-8')
except Exception as e:
print(f"Error decompressing session data for key {key}: {str(e)}")
return value
return value
except Exception as e:
print(f"Error in get_from_session for key {key}: {str(e)}")
return default
def store_in_session(key, value):
"""Store data in session with automatic compression for large values"""
try:
if value is None:
session[key] = None
return
# For strings, compress if they're large
if isinstance(value, str) and len(value) > 1000:
try:
compressed = zlib.compress(value.encode('utf-8'))
b64_compressed = base64.b64encode(compressed).decode('ascii')
session[key] = f"__COMPRESSED__{b64_compressed}"
except Exception as e:
print(f"Error compressing data for key {key}: {str(e)}")
session[key] = value
else:
session[key] = value
# Verify storage was successful
if key not in session:
print(f"Warning: Failed to store {key} in session")
except Exception as e:
print(f"Error in store_in_session for key {key}: {str(e)}")
# Make a best effort to store something
try:
session[key] = str(value)[:200] + "... (truncated due to error)"
except:
pass
def format_questions_html(questions_content):
"""
Format questions and answers into proper HTML structure with spoiler buttons.
This function prevents nesting questions inside each other when refreshing.
"""
# Make sure re module is properly imported
import re
# If input is empty, return empty string
if not questions_content or questions_content.strip() == "":
print("Empty questions content, returning empty string")
return ""
# Try to extract question-answer pairs
question_answer_pairs = []
# First check if the content already has the expected HTML structure
if "<div class=\"question-container\">" in questions_content:
print("Questions content already has HTML structure, adding show/hide buttons if needed")
# Check if 'show-answer-btn' already exists in the content
if "show-answer-btn" not in questions_content:
# Replace the existing structure with one that includes buttons
processed_html = re.sub(
r'<div class="question-container">\s*<h3[^>]*>(.*?)</h3>\s*<div class="answer[^"]*"[^>]*>(.*?)</div>\s*</div>',
r'<div class="question-container">\n <h3>\1</h3>\n <button class="show-answer-btn">\n <span>Show Answer</span>\n <i class="fas fa-chevron-down"></i>\n </button>\n <div class="answer hidden">\2</div>\n</div>',
questions_content,
flags=re.DOTALL
)
return processed_html
return questions_content
# Try different formats if it's not HTML already
try:
# First check if the content already has questions and answers
q_pattern = r'Question:\s*(.*?)(?=Answer:|$)'
a_pattern = r'Answer:\s*(.*?)(?=Question:|$)'
q_matches = re.findall(q_pattern, questions_content, re.DOTALL)
a_matches = re.findall(a_pattern, questions_content, re.DOTALL)
# Pair questions with answers
for i in range(min(len(q_matches), len(a_matches))):
q = q_matches[i].strip()
a = a_matches[i].strip()
question_answer_pairs.append((q, a))
# If no pairs found yet, try splitting by question
if not question_answer_pairs:
parts = re.split(r'^\s*Question:', questions_content, flags=re.MULTILINE)
if len(parts) > 1:
for part in parts[1:]: # Skip first empty part
lines = part.strip().split('\n')
q = lines[0].strip()
a = '\n'.join(lines[1:]).strip()
if q and a:
question_answer_pairs.append((q, a))
except Exception as e:
print(f"Error parsing questions: {e}")
# Continue with whatever pairs we found
# If we couldn't extract any pairs, create a default one
if not question_answer_pairs:
question_answer_pairs = [
("What does this document discuss?", "The document content could not be processed.")
]
# Helper function to process markdown-style formatting
def process_markdown(text):
# Convert **text** to <strong>text</strong> - more robust pattern matching
# This pattern handles both inline and multi-word bold formatting
processed = re.sub(r'\*\*([^*]+?)\*\*', r'<strong>\1</strong>', text)
# Also handle underscores for emphasis (_text_) -> <em>text</em>
processed = re.sub(r'\_([^_]+?)\_', r'<em>\1</em>', processed)
# Handle bullet points
processed = re.sub(r'^\s*\*\s+(.+)$', r'<li>\1</li>', processed, flags=re.MULTILINE)
# Wrap consecutive list items in ul tags
if '<li>' in processed:
processed = re.sub(r'(<li>.*?</li>)+', r'<ul>\g<0></ul>', processed, flags=re.DOTALL)
return processed
# Build HTML output with Show/Hide buttons
html_output = ""
for q, a in question_answer_pairs:
# Make sure question has "Question:" prefix if it doesn't already
if not q.lower().startswith("question:"):
q = f"Question: {q}"
# Apply markdown processing
q = process_markdown(q)
a = process_markdown(a)
# Create clean answer format
if a.lower().startswith("answer:"):
# Remove the "Answer:" prefix since we'll add it as a separate element
a = re.sub(r'^answer:\s*', '', a, flags=re.IGNORECASE)
html_output += f"""<div class="question-container">
<h3 class="text-purple-700">{q}</h3>
<button class="show-answer-btn">
<span>Show Answer</span>
<i class="fas fa-chevron-down"></i>
</button>
<div class="answer hidden">
<p><span class="answer-label">Answer:</span> {a}</p>
</div>
</div>
"""
# Add JavaScript for functionality
html_output += """
<script>
document.addEventListener('DOMContentLoaded', function() {
// Initialize show/hide buttons
const buttons = document.querySelectorAll('.show-answer-btn');
console.log('Found ' + buttons.length + ' Show Answer buttons');
buttons.forEach(function(button) {
button.addEventListener('click', function() {
const answer = this.nextElementSibling;
const span = this.querySelector('span');
const icon = this.querySelector('i');
if (answer.classList.contains('hidden')) {
// Show answer
answer.classList.remove('hidden');
span.textContent = 'Hide Answer';
icon.className = 'fas fa-chevron-up';
} else {
// Hide answer
answer.classList.add('hidden');
span.textContent = 'Show Answer';
icon.className = 'fas fa-chevron-down';
}
});
});
});
</script>
"""
return html_output
@app.route("/signin", methods=["GET", "POST"])
def signin():
# Check if user is already logged in
if "user" in session:
return redirect(url_for("upload_file"))
# Check if form is submitted
if request.method == "POST":
# Get form data
email = request.form.get("email")
password = request.form.get("password")
# Validate form data
if not email or not password:
flash("Please fill out all fields.", "error")
return render_template("signin.html", csrf_token=generate_csrf())
# Check if email is valid
if not is_valid_email(email):
flash("Invalid email format.", "error")
return render_template("signin.html", csrf_token=generate_csrf())
# Check if password is valid
if not is_valid_password(password):
flash("Invalid password format.", "error")
return render_template("signin.html", csrf_token=generate_csrf())
try:
conn = sqlite3.connect("users.db")
cursor = conn.cursor()
# Check if user exists
cursor.execute("SELECT * FROM users WHERE email = ?", (email,))
user = cursor.fetchone()
if user:
# Check if password is correct
if check_password_hash(user[2], password):
# Generate remember token
remember_token = generate_remember_token()
# Update user record with remember token
cursor.execute("UPDATE users SET remember_token = ? WHERE id = ?", (remember_token, user[0]))
conn.commit()
# Set session variables
session["user"] = email
session["remember_token"] = remember_token
flash("Logged in successfully!", "success")
return redirect(url_for("upload_file"))
else:
flash("Invalid email or password.", "error")
return render_template("signin.html", csrf_token=generate_csrf())
else:
flash("User not found. Please check your email and password.", "error")
return render_template("signin.html", csrf_token=generate_csrf())
except Exception as e:
print(f"Error logging in: {str(e)}")
flash("An error occurred. Please try again.", "error")
finally:
conn.close()
return render_template("signin.html", csrf_token=generate_csrf())
@app.route("/signup", methods=["GET", "POST"])
def signup():
# Check if user is already logged in
if "user" in session:
return redirect(url_for("upload_file"))
# Check if form is submitted
if request.method == "POST":
# Get form data
email = request.form.get("email")
password = request.form.get("password")
confirm_password = request.form.get("confirm_password")
terms = request.form.get("terms")
# Validate form data
if not email or not password or not confirm_password:
flash("Please fill out all fields.", "error")
return render_template("signup.html", csrf_token=generate_csrf())
# Check if email is valid
if not is_valid_email(email):
flash("Invalid email format.", "error")
return render_template("signup.html", csrf_token=generate_csrf())
# Check if passwords match
if password != confirm_password:
flash("Passwords do not match.", "error")
return render_template("signup.html", csrf_token=generate_csrf())
# Check if password is valid
if not is_valid_password(password):
flash("Invalid password format. Password must contain at least 8 characters, including uppercase, lowercase, and numbers.", "error")
return render_template("signup.html", csrf_token=generate_csrf())
# Check if terms are accepted
if not terms:
flash("You must accept the Terms of Service and Privacy Policy.", "error")
return render_template("signup.html", csrf_token=generate_csrf())
try:
conn = sqlite3.connect("users.db")
cursor = conn.cursor()
# Check if user already exists
cursor.execute("SELECT * FROM users WHERE email = ?", (email,))
user = cursor.fetchone()
if user:
flash("User already exists. Please sign in instead.", "error")
return render_template("signup.html", csrf_token=generate_csrf())
else:
# Hash the password
hashed_password = generate_password_hash(password)
# Generate remember token
remember_token = generate_remember_token()
# Create new user
cursor.execute(
"INSERT INTO users (email, password, remember_token) VALUES (?, ?, ?)",
(email, hashed_password, remember_token)
)
conn.commit()
# Set session variables
session["user"] = email
session["remember_token"] = remember_token
flash("Account created successfully!", "success")
return redirect(url_for("upload_file"))
except Exception as e:
print(f"Error creating user: {str(e)}")
flash("An error occurred. Please try again.", "error")
finally:
conn.close()
return render_template("signup.html", csrf_token=generate_csrf())
@app.route("/logout")
def logout():
# Clear remember token from database
if "user" in session:
try:
conn = sqlite3.connect("users.db")
cursor = conn.cursor()
cursor.execute("UPDATE users SET remember_token = NULL WHERE email = ?",
(session["user"],))
conn.commit()
conn.close()
except Exception as e:
print(f"Error clearing remember token: {str(e)}")
# Continue with logout even if token clearing fails
# Clear session
session.clear()
# Create response and clear cookie
response = redirect(url_for("signin"))
response.delete_cookie('remember_token')
flash("You have been logged out successfully.", "success")
return response
@app.route("/settings", methods=["GET", "POST"])
def settings():
"""User settings page to manage account and preferences"""
# Check if user is logged in
if "user" not in session:
flash("Please sign in to access settings.", "error")
return redirect(url_for("signin"))
user_email = session["user"]
try:
# Connect to database
conn = sqlite3.connect("users.db")
cursor = conn.cursor()
# Get user information
cursor.execute("SELECT * FROM users WHERE email = ?", (user_email,))
user = cursor.fetchone()
if not user:
flash("User not found.", "error")
return redirect(url_for("signin"))
# Create user settings table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS user_settings (
user_id INTEGER PRIMARY KEY,
openai_api_key TEXT,
google_translate_key TEXT,
clear_history INTEGER DEFAULT 1,
save_extracted_text INTEGER DEFAULT 0,
default_language TEXT DEFAULT 'en',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
conn.commit()
# Check if settings exist for this user
cursor.execute("SELECT * FROM user_settings WHERE user_id = ?", (user[0],))
user_settings = cursor.fetchone()
# Initialize settings
openai_api_key = ""
google_translate_key = ""
clear_history = True
save_extracted_text = False
default_language = "en"
# Load existing settings if available
if user_settings:
openai_api_key = user_settings[1] or ""
google_translate_key = user_settings[2] or ""
clear_history = bool(user_settings[3])
save_extracted_text = bool(user_settings[4])
default_language = user_settings[5] or "en"
# Handle form submission
if request.method == "POST":
# Form validation
current_password = request.form.get("current_password", "")
new_password = request.form.get("new_password", "")
confirm_password = request.form.get("confirm_password", "")
# Get API keys
new_openai_api_key = request.form.get("openai_api_key", "")
new_google_translate_key = request.form.get("google_translate_key", "")
# Get preferences
new_clear_history = "clear_history" in request.form
new_save_extracted_text = "save_extracted_text" in request.form
new_default_language = request.form.get("default_language", "en")
# Process password change if requested
if current_password and new_password:
if new_password != confirm_password:
flash("New passwords do not match.", "error")
else:
# Verify current password
if check_password_hash(user[2], current_password):
# Password validation
if is_valid_password(new_password):
# Update password
hashed_password = generate_password_hash(new_password)
cursor.execute("UPDATE users SET password = ? WHERE id = ?",
(hashed_password, user[0]))
conn.commit()
flash("Password updated successfully.", "success")
else:
flash("Password must contain at least 8 characters, including uppercase, lowercase, and numbers.", "error")
else:
flash("Current password is incorrect.", "error")
# Update user settings
if user_settings:
# Update existing settings
cursor.execute("""
UPDATE user_settings
SET openai_api_key = ?, google_translate_key = ?, clear_history = ?,
save_extracted_text = ?, default_language = ?, updated_at = CURRENT_TIMESTAMP
WHERE user_id = ?
""", (new_openai_api_key, new_google_translate_key, int(new_clear_history),
int(new_save_extracted_text), new_default_language, user[0]))
else:
# Insert new settings
cursor.execute("""
INSERT INTO user_settings
(user_id, openai_api_key, google_translate_key, clear_history,
save_extracted_text, default_language)
VALUES (?, ?, ?, ?, ?, ?)
""", (user[0], new_openai_api_key, new_google_translate_key,
int(new_clear_history), int(new_save_extracted_text), new_default_language))
conn.commit()
# Update local variables to reflect new settings
openai_api_key = new_openai_api_key
google_translate_key = new_google_translate_key
clear_history = new_clear_history
save_extracted_text = new_save_extracted_text
default_language = new_default_language
# Update session language
session["selected_language"] = default_language
# Apply OpenAI API key to environment if provided
if new_openai_api_key:
os.environ["OPENAI_API_KEY"] = new_openai_api_key
# Apply Google Translate API key to environment if provided
if new_google_translate_key:
os.environ["GOOGLE_TRANSLATE_API_KEY"] = new_google_translate_key
flash("Settings saved successfully.", "success")
# Close database connection
conn.close()
# Render settings template with user info and settings
return render_template("settings.html",
user_email=user_email,
openai_api_key=openai_api_key,
google_translate_key=google_translate_key,
clear_history=clear_history,
save_extracted_text=save_extracted_text,
default_language=default_language,
csrf_token=generate_csrf())
except Exception as e:
print(f"Error in settings page: {str(e)}")
flash(f"An error occurred: {str(e)}", "error")
return redirect(url_for("upload_file"))
# --- PDF Text Extraction ---
def extract_text_from_pdf(pdf_path):
try:
doc = fitz.open(pdf_path)
extracted_text = ""
for page in doc:
try:
text = page.get_text("text")
if text.strip():
extracted_text += text + "\n"
else:
# Try OCR if text extraction gives no results
try:
pix = page.get_pixmap() # Convert page to an image
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
ocr_text = pytesseract.image_to_string(img)
if ocr_text.strip():
extracted_text += ocr_text + "\n"
print(f"Used OCR for page {page.number} of PDF")
except Exception as ocr_err:
print(f"OCR error on page {page.number}: {str(ocr_err)}")
# Continue without OCR if it fails
except Exception as page_err:
print(f"Error processing page {page.number}: {str(page_err)}")
# Continue with next page if one fails
# If we got some text, return it; otherwise use a fallback message
if extracted_text.strip():
return extracted_text.strip()
else:
print("No text was extracted from the PDF")
return "Text extraction failed. This may be a scanned or image-based PDF that requires OCR."
except Exception as e:
print(f"Error opening or processing PDF: {str(e)}")
# Return a default text so the process can continue
return "Sample text for processing. The PDF could not be read correctly."
# --- OCR for Scanned PDFs ---
def extract_text_from_image(image_path):
text = pytesseract.image_to_string(Image.open(image_path))
return text if text.strip() else "No text detected."
def extract_text_from_txt(txt_path):
"""Extract text from a .txt file"""
try:
with open(txt_path, 'r', encoding='utf-8') as file:
text = file.read()
return text if text.strip() else "No text found in the text file."
except UnicodeDecodeError:
# Try with a different encoding if UTF-8 fails
try:
with open(txt_path, 'r', encoding='latin-1') as file:
text = file.read()
print("Used latin-1 encoding for text file")
return text if text.strip() else "No text found in the text file."
except Exception as e:
print(f"Error reading text file with latin-1 encoding: {str(e)}")
return "Could not read the text file. The file may be corrupted."
except Exception as e:
print(f"Error reading text file: {str(e)}")
return "Error reading the text file: " + str(e)
# --- Text Summarization ---
def summarize_text(text):
try:
# Limit text length to prevent API issues
max_text_length = 8000
original_length = len(text)
if len(text) > max_text_length:
print(f"Truncating text for summarization from {original_length} to {max_text_length} characters")
# Take beginning and end
half_length = max_text_length // 2
text = text[:half_length] + "\n...\n" + text[-half_length:]
api_url = "https://api.qewertyy.dev/models"
payload = {
"model_id": 5, # GPT-3.5 Turbo
"messages": [
{
"role": "user",
"content": SUMMARY_PROMPT.format(text=text)
}
]
}
headers = {"Content-Type": "application/json"}
# Limit timeout to avoid hanging
print(f"Calling summarization API with {len(text)} characters")
response = requests.post(api_url, json=payload, headers=headers, timeout=15)
print(f"Summarization API response status: {response.status_code}")
if response.status_code == 200:
data = response.json()
summary = data.get("content", "")
if summary:
print(f"Got summary of {len(summary)} characters")
return summary
else:
print("API returned empty summary content")
else:
print(f"API summary generation failed: Status code {response.status_code}, Response: {response.text}")
# If we get here, either the request failed or returned no summary
print("Using fallback summary method")
# Fallback to a basic summary (first few sentences + last few sentences)
sentences = text.split('.')
first_part = '.'.join(sentences[:4]) + '.'
last_part = '.'.join(sentences[-4:]) + '.'
summary = f"{first_part}\n...\n{last_part}\n\nNote: This is an auto-generated excerpt as the summary API failed."
return summary
except requests.exceptions.Timeout:
print("Summary API request timed out")
# Create a simple summary from the text
sentences = text.split('.')
if len(sentences) > 8:
summary = '.'.join(sentences[:4]) + '.\n...\n' + '.'.join(sentences[-4:]) + '.'
else:
summary = '.'.join(sentences[:min(4, len(sentences))]) + '.'
return f"{summary}\n\nNote: This is an auto-generated excerpt as the summary API timed out."
except Exception as e:
print(f"Error in summarization: {str(e)}")
# Return a basic summary to prevent workflow interruption
return "Summary generation failed. The system is experiencing issues with the summarization API."
# --- Question Generation ---
def generate_questions(text):
try:
# Limit text length to prevent API issues
max_text_length = 8000
original_length = len(text)
if len(text) > max_text_length:
print(f"Truncating text for question generation from {original_length} to {max_text_length} characters")
# Take beginning and middle sections
third_length = max_text_length // 3
text = text[:third_length] + "\n...\n" + text[len(text)//2-third_length//2:len(text)//2+third_length//2] + "\n...\n" + text[-third_length:]
# Modified prompt that includes the Show Answer button and emphasizes questions MUST be based on the text content
questions_prompt = """Generate 10 questions and answers based STRICTLY on the provided text content only. Do not invent information.
Format each question and answer exactly as follows:
<div class="question-container">
<h3 class="text-purple-700">Question: [specific question about the text content]</h3>
<button class="show-answer-btn">
<span>Show Answer</span>
<i class="fas fa-chevron-down"></i>
</button>
<div class="answer hidden">
<p><span class="answer-label">Answer:</span> [answer based on information from the text]</p>
</div>
</div>
Important instructions:
1. ONLY ask questions that can be directly answered from the text content provided
2. Make sure questions are specific and not generic or unrelated to the content
3. Make important terms or keywords in answers bold using HTML <strong> tags
4. Each answer must cite specific information from the text
5. Do NOT create questions about topics not covered in the text
Text to generate questions from:
{text}"""
# Try first with the qewertyy API
try:
print(f"Attempting to call qewertyy API for question generation")
api_url = "https://api.qewertyy.dev/models"
payload = {
"model_id": 5, # GPT-3.5 Turbo
"messages": [
{
"role": "user",
"content": questions_prompt.format(text=text)
}
]
}
headers = {"Content-Type": "application/json"}
print("Sending API request for question generation...")
# Limit timeout to avoid hanging
response = requests.post(api_url, json=payload, headers=headers, timeout=20)
print(f"qewertyy API response status: {response.status_code}")
if response.status_code == 200:
data = response.json()
questions = data.get("content", "")
# Print detailed debugging information
print(f"API response length: {len(str(data))} characters")
print(f"Content field length: {len(questions)} characters")
if not questions:
print("API returned empty content field")
elif len(questions) < 50:
print(f"API returned very short content: '{questions}'")
# More specific check for valid content
if questions and "<div class=\"question-container\">" in questions:
print(f"Got valid questions of {len(questions)} characters")
# Add script if it's not already there
if "</script>" not in questions:
questions += add_show_answer_script()
return questions
else:
print("API returned invalid HTML structure for questions")
# Try to debug what was returned instead
content_preview = questions[:200] + "..." if len(questions) > 200 else questions
print(f"Content preview: {content_preview}")
else:
print(f"API question generation failed: Status code {response.status_code}, Response: {response.text[:500]}")
# If still here, try with a simplified prompt
print("Attempting with simplified API prompt...")
simplified_prompt = """Generate 10 specific questions and detailed answers based ONLY on this text content.
Each question should be formatted as 'Question: [question]' and each answer as 'Answer: [answer]'.
Make answers detailed and informative. Use <strong> tags to highlight important terms.
Text content:
{text}"""
simplified_payload = {
"model_id": 5, # GPT-3.5 Turbo
"messages": [
{
"role": "user",
"content": simplified_prompt.format(text=text)
}
]
}
response = requests.post(api_url, json=simplified_payload, headers=headers, timeout=20)
print(f"Simplified API request response status: {response.status_code}")
if response.status_code == 200:
data = response.json()
raw_questions = data.get("content", "")
if raw_questions and ("Question:" in raw_questions or "question:" in raw_questions):
print(f"Got raw questions content: {len(raw_questions)} characters")
# Format the raw questions into HTML
formatted_questions = format_questions_html(raw_questions)
return formatted_questions
else:
print("Simplified API request also failed to return valid content")
# If first API fails, try with OpenAI API if available
openai_api_key = os.environ.get('OPENAI_API_KEY')
if openai_api_key:
try:
print("Attempting to use OpenAI API for question generation")
import openai
openai.api_key = openai_api_key
completion = openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant that generates specific questions and answers about text content."},
{"role": "user", "content": questions_prompt.format(text=text)}
],
temperature=0.7,
max_tokens=2000
)
questions = completion.choices[0].message.content
if questions and "<div class=\"question-container\">" in questions:
# Add script if it's not already there
if "</script>" not in questions:
questions += add_show_answer_script()
return questions
except Exception as openai_error:
print(f"OpenAI API error: {str(openai_error)}")
except Exception as api_error:
print(f"API error: {str(api_error)}")
# If all APIs fail, use our improved local model for question generation
try:
import nltk
from nltk.tokenize import sent_tokenize
import re
# Download necessary NLTK data if not present
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download('punkt')