Spaces:
Sleeping
Sleeping
File size: 68,992 Bytes
3e42629 3b3e0b9 3e42629 bb4f8ed 3b3e0b9 b3ad8fa 3b3e0b9 b3ad8fa 3b3e0b9 9fa396f 3b3e0b9 2940309 3b3e0b9 2940309 3b3e0b9 3e42629 3b3e0b9 3e42629 296015b 8e51ed8 1fd1e18 3e42629 1fd1e18 3e42629 2940309 296015b 3e42629 296015b 3b3e0b9 4466fc1 3b3e0b9 3e42629 3b3e0b9 3e42629 3b3e0b9 3e42629 3b3e0b9 3e42629 3b3e0b9 3e42629 4466fc1 3e42629 3b3e0b9 4466fc1 3b3e0b9 3e42629 4466fc1 3e42629 3b3e0b9 3e42629 3b3e0b9 3e42629 3b3e0b9 3e42629 3b3e0b9 3e42629 3b3e0b9 3e42629 3b3e0b9 3e42629 3b3e0b9 3e42629 8e51ed8 3e42629 8e51ed8 3e42629 8e51ed8 3e42629 8e51ed8 3e42629 8e51ed8 3e42629 8e51ed8 3e42629 8e51ed8 3b3e0b9 8e51ed8 3b3e0b9 8e51ed8 3b3e0b9 8e51ed8 3b3e0b9 3e42629 3b3e0b9 3e42629 3b3e0b9 3e42629 3b3e0b9 1fd1e18 3b3e0b9 1fd1e18 3b3e0b9 1fd1e18 3e42629 3b3e0b9 3e42629 3b3e0b9 3e42629 3b3e0b9 3e42629 4466fc1 3e42629 3b3e0b9 1fd1e18 3e42629 3b3e0b9 4466fc1 3e42629 3b3e0b9 3e42629 4466fc1 3e42629 3b3e0b9 |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 |
import PyPDF2
import re
from collections import Counter
import os
import nltk
import transformers, logging, contextlib
def setup_cache_directories():
"""Setup cache directories for transformers and torch with proper permissions"""
try:
# Create cache directories in /app with proper permissions
cache_dirs = {
'HF_HOME': '/app/.cache/huggingface',
'TORCH_HOME': '/app/.cache/torch'
}
for env_var, path in cache_dirs.items():
os.makedirs(path, exist_ok=True)
os.chmod(path, 0o777)
os.environ[env_var] = path
# print(f"Cache directories setup complete: {cache_dirs}")
except Exception as e:
print(f"Warning: Cache directory setup failed: {e}")
# Set NLTK data path BEFORE any other NLTK imports
def setup_nltk_data():
"""Setup NLTK data directory in container-writable location"""
try:
# Silence HuggingFace / Transformers logging
transformers.utils.logging.set_verbosity_error()
logging.getLogger("transformers").setLevel(logging.ERROR)
# Use the app directory for NLTK data in container
nltk_data_dir = '/app/nltk_data'
# Ensure directory exists and is writable
os.makedirs(nltk_data_dir, exist_ok=True)
# Set NLTK data path - this must be done first
nltk.data.path.clear()
nltk.data.path.append(nltk_data_dir)
# Also set the NLTK_DATA environment variable
os.environ['NLTK_DATA'] = nltk_data_dir
# Setup cache directories for transformers and torch
setup_cache_directories()
# Download required resources if not present
required_resources = [
'punkt',
'punkt_tab',
'stopwords',
'wordnet',
'omw-1.4'
]
for resource in required_resources:
try:
nltk.data.find(f'tokenizers/{resource}' if 'punkt' in resource else f'corpora/{resource}')
except LookupError:
with contextlib.redirect_stdout(None):
with contextlib.redirect_stderr(None):
try:
nltk.download(resource, download_dir=nltk_data_dir, quiet=True)
except:
pass # completely silent fallback
except Exception as e:
print(f"Warning: NLTK setup failed: {e}")
# Call setup immediately after basic imports
setup_nltk_data()
# Now import NLTK modules after setup
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import string
from datetime import datetime, timedelta
import json
import torch
from transformers import T5ForConditionalGeneration, T5Tokenizer, pipeline, BlipProcessor, BlipForConditionalGeneration, AutoTokenizer, AutoModelForSeq2SeqLM
import warnings
import fitz # PyMuPDF
from PIL import Image, ImageEnhance, ImageFilter
import io
import base64
import os
import pytesseract
import hashlib
import logging
import getpass
import tempfile
import shutil
import numpy as np
import requests
import urllib3
from fastapi import FastAPI, UploadFile, File, Form
from fastapi.staticfiles import StaticFiles
try:
import psycopg2
PSYCOPG2_AVAILABLE = True
except ImportError:
PSYCOPG2_AVAILABLE = False
print("Warning: psycopg2 not available. Database features will be disabled.")
from pydantic import BaseModel
from typing import List, Dict, Any, Optional
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
try:
import cv2
import numpy as np
OPENCV_AVAILABLE = True
except ImportError:
# print("OpenCV not available. Using PIL for image preprocessing.")
from PIL import Image
OPENCV_AVAILABLE = False
from questions import THESIS_QUESTIONS
from biomed_annotator import generate_annotations
warnings.filterwarnings('ignore')
app = FastAPI(title='AI (PDFβSummary+QnA+Scores)', version='0.2.1')
app.mount("/static", StaticFiles(directory="static"), name="static")
class HIPAALogger:
"""HIPAA-compliant audit logging system"""
def __init__(self, log_file="hipaa_audit.log"):
# Create logs directory if it doesn't exist
log_dir = '/app/logs'
os.makedirs(log_dir, exist_ok=True)
# Use the new log file path
self.log_file = os.path.join(log_dir, log_file)
self.logger = None
self.setup_logging()
def setup_logging(self):
"""Setup secure audit logging with fallback to console"""
try:
# Try to create file handler
logging.basicConfig(
filename=self.log_file,
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
self.logger = logging.getLogger('HIPAA_AUDIT')
print(f"HIPAA logging initialized: {self.log_file}")
except PermissionError:
# Fallback to console logging if file writing fails
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
self.logger = logging.getLogger('HIPAA_AUDIT')
print(f"Warning: Cannot write to {self.log_file}, using console logging")
except Exception as e:
# Fallback to console logging for any other error
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
self.logger = logging.getLogger('HIPAA_AUDIT')
print(f"Warning: Logging setup failed ({e}), using console logging")
def log_access(self, user_id, action, resource, success=True):
"""Log access attempts and actions"""
status = "SUCCESS" if success else "FAILURE"
message = f"USER:{user_id} ACTION:{action} RESOURCE:{resource} STATUS:{status}"
self.logger.info(message)
def log_phi_processing(self, user_id, document_hash, action):
"""Log PHI processing events"""
message = f"PHI_PROCESSING USER:{user_id} DOC_HASH:{document_hash} ACTION:{action}"
self.logger.info(message)
class SecureFileHandler:
"""Secure file handling with encryption and secure deletion"""
def __init__(self, password=None):
self.password = password
self.key = self._derive_key(password) if password else None
self.fernet = Fernet(self.key) if self.key else None
def _derive_key(self, password):
"""Derive encryption key from password"""
password_bytes = password.encode()
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=b'hipaa_thesis_analyzer_salt',
iterations=100000,
)
key = base64.urlsafe_b64encode(kdf.derive(password_bytes))
return key
def encrypt_data(self, data):
"""Encrypt sensitive data"""
if not self.fernet:
return data
if isinstance(data, str):
data = data.encode()
return self.fernet.encrypt(data)
def decrypt_data(self, encrypted_data):
"""Decrypt sensitive data"""
if not self.fernet:
return encrypted_data
decrypted = self.fernet.decrypt(encrypted_data)
return decrypted.decode()
def secure_save(self, data, filepath):
"""Save data with encryption"""
try:
if self.fernet:
encrypted_data = self.encrypt_data(json.dumps(data))
with open(filepath + '.enc', 'wb') as f:
f.write(encrypted_data)
else:
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
except PermissionError:
print(f"Warning: Cannot write to {filepath}, saving to /tmp instead")
# Fallback to /tmp directory
import tempfile
temp_path = os.path.join(tempfile.gettempdir(), os.path.basename(filepath))
if self.fernet:
encrypted_data = self.encrypt_data(json.dumps(data))
with open(temp_path + '.enc', 'wb') as f:
f.write(encrypted_data)
else:
with open(temp_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
print(f"Data saved to: {temp_path}")
except Exception as e:
print(f"Error saving data: {e}")
# Still try to save to /tmp as last resort
try:
import tempfile
temp_path = os.path.join(tempfile.gettempdir(), os.path.basename(filepath))
if self.fernet:
encrypted_data = self.encrypt_data(json.dumps(data))
with open(temp_path + '.enc', 'wb') as f:
f.write(encrypted_data)
else:
with open(temp_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
print(f"Data saved to fallback location: {temp_path}")
except Exception as fallback_error:
print(f"Failed to save data even to fallback location: {fallback_error}")
def secure_load(self, filepath):
"""Load encrypted data"""
if self.fernet and os.path.exists(filepath + '.enc'):
with open(filepath + '.enc', 'rb') as f:
encrypted_data = f.read()
decrypted_data = self.decrypt_data(encrypted_data)
return json.loads(decrypted_data)
elif os.path.exists(filepath):
with open(filepath, 'r', encoding='utf-8') as f:
return json.load(f)
return None
def secure_delete(self, filepath):
"""Securely delete files by overwriting"""
if os.path.exists(filepath):
# Overwrite file multiple times before deletion
file_size = os.path.getsize(filepath)
with open(filepath, 'rb+') as f:
for _ in range(3): # DoD 5220.22-M standard
f.seek(0)
f.write(os.urandom(file_size))
f.flush()
os.remove(filepath)
# Also check for encrypted version
if os.path.exists(filepath + '.enc'):
file_size = os.path.getsize(filepath + '.enc')
with open(filepath + '.enc', 'rb+') as f:
for _ in range(3):
f.seek(0)
f.write(os.urandom(file_size))
f.flush()
os.remove(filepath + '.enc')
class HIPAACompliantThesisAnalyzer:
"""HIPAA-compliant version of the thesis analyzer"""
def __init__(self, user_id=None, password=None, session_timeout=30, model_name="t5-small", mode="analyze"):
self.user_id = user_id or getpass.getuser()
self.session_timeout = session_timeout # minutes
self.session_start = datetime.now()
self.last_activity = datetime.now()
self.model_name = model_name
self.mode = mode
# Map model names to their optimal tasks and parameters
self.model_configs = {
"t5-small": {"task": "text2text-generation", "summarizer_task": "summarization"},
"t5-base": {"task": "text2text-generation", "summarizer_task": "summarization"},
"t5-large": {"task": "text2text-generation", "summarizer_task": "summarization"},
"bart-large-cnn": {"task": "text2text-generation", "summarizer_task": "summarization"},
"facebook/bart-base": {"task": "text2text-generation", "summarizer_task": "summarization"},
"distilbart-cnn-12-6": {"task": "text2text-generation", "summarizer_task": "summarization"},
"sshleifer/distilbart-cnn-6-6": {"task": "text2text-generation", "summarizer_task": "summarization"},
"pegasus-large": {"task": "text2text-generation", "summarizer_task": "summarization"},
"flan-t5-base": {"task": "text2text-generation", "summarizer_task": "summarization"},
"flan-t5-large": {"task": "text2text-generation", "summarizer_task": "summarization"}
}
# Initialize HIPAA compliance components
self.hipaa_logger = HIPAALogger()
self.secure_handler = SecureFileHandler(password)
# Log session start
self.hipaa_logger.log_access(self.user_id, "SESSION_START", "THESIS_ANALYZER")
# Initialize base analyzer components
self._initialize_analyzer()
print(f"HIPAA-Compliant Thesis Analyzer initialized for user: {self.user_id}")
print(f"Session timeout: {session_timeout} minutes")
print(f"Encryption enabled: {'Yes' if password else 'No'}")
print(f"Mode: {self.mode}")
def _initialize_analyzer(self):
"""Initialize the core analyzer components"""
try:
self.lemmatizer = WordNetLemmatizer()
self.stop_words = set(stopwords.words('english'))
except LookupError as e:
print(f"NLTK resource error: {e}")
self._download_nltk_resources()
try:
self.lemmatizer = WordNetLemmatizer()
self.stop_words = set(stopwords.words('english'))
except Exception as e2:
print(f"Failed to initialize NLTK after download: {e2}")
# Fallback to basic functionality
self.lemmatizer = None
self.stop_words = set(['the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by'])
except Exception as e:
print(f"Error initializing NLTK: {e}")
# Fallback to basic functionality
self.lemmatizer = None
self.stop_words = set(['the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by'])
self.thesis_text = ""
self.sentences = []
self.key_terms = []
self.extracted_images = []
self.image_descriptions = []
self.ocr_results = []
self.use_ocr = True
self.use_blip = True
# Initialize Model
print(f"Loading {self.model_name} model (HIPAA-compliant local processing)...")
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
try:
# Try to load with explicit cache directory
cache_dir = '/app/.cache/huggingface'
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, cache_dir=cache_dir)
self.model = AutoModelForSeq2SeqLM.from_pretrained(self.model_name, cache_dir=cache_dir)
self.model.to(self.device)
print(f"{self.model_name} loaded successfully from cache")
except Exception as e:
print(f"Error loading {self.model_name}: {e}")
print("Attempting to load with fallback cache directory...")
try:
# Fallback to default cache
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
self.model = AutoModelForSeq2SeqLM.from_pretrained(self.model_name)
self.model.to(self.device)
print(f"{self.model_name} loaded with fallback cache")
except Exception as e2:
print(f"Failed to load {self.model_name}: {e2}")
# Fallback to t5-small if requested model fails
if self.model_name != "t5-small":
print("Falling back to t5-small...")
self.model_name = "t5-small"
self.tokenizer = AutoTokenizer.from_pretrained("t5-small")
self.model = AutoModelForSeq2SeqLM.from_pretrained("t5-small")
self.model.to(self.device)
else:
raise e2
# Initialize pipelines
try:
self.summarizer = pipeline(
"summarization",
model=self.model,
tokenizer=self.tokenizer,
device=0 if torch.cuda.is_available() else -1,
max_length=200,
min_length=50,
do_sample=True,
temperature=0.7
)
self.qa_pipeline = pipeline(
"text2text-generation",
model=self.model,
tokenizer=self.tokenizer,
device=0 if torch.cuda.is_available() else -1,
max_length=512,
do_sample=True,
temperature=0.7
)
print("Pipelines initialized successfully")
except Exception as e:
print(f"Error initializing pipelines: {e}")
# Create fallback pipelines
self.summarizer = None
self.qa_pipeline = None
# Initialize BLIP if enabled
if self.use_blip:
try:
self.blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
self.blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
self.blip_model.to(self.device)
print("BLIP model loaded for local image analysis")
except Exception as e:
print(f"BLIP model loading failed: {e}")
self.use_blip = False
# Check OCR availability
if self.use_ocr:
try:
pytesseract.get_tesseract_version()
print("Tesseract OCR available for local processing")
except Exception as e:
print(f"Tesseract OCR not available: {e}")
self.use_ocr = False
def _download_nltk_resources(self):
"""Download required NLTK resources to user directory"""
# Use the same user-writable directory
nltk_data_dir = os.path.join(os.path.expanduser('~'), 'nltk_data')
os.makedirs(nltk_data_dir, exist_ok=True)
nltk.data.path.append(nltk_data_dir)
resources = [
('tokenizers/punkt', 'punkt'),
('tokenizers/punkt_tab', 'punkt_tab'),
('corpora/stopwords', 'stopwords'),
('corpora/wordnet', 'wordnet'),
('corpora/omw-1.4', 'omw-1.4')
]
for resource_path, resource_name in resources:
try:
nltk.data.find(resource_path)
except LookupError:
try:
nltk.download(resource_name, download_dir=nltk_data_dir, quiet=True)
print(f"Downloaded NLTK resource: {resource_name}")
except Exception as e:
print(f"Warning: Failed to download {resource_name}: {e}")
def check_session_timeout(self):
"""Check if session has timed out"""
time_since_start = datetime.now() - self.session_start
time_since_activity = datetime.now() - self.last_activity
if time_since_activity.total_seconds() > (self.session_timeout * 60):
self.hipaa_logger.log_access(self.user_id, "SESSION_TIMEOUT", "THESIS_ANALYZER")
raise Exception("Session timed out due to inactivity. Please restart for security.")
self.last_activity = datetime.now()
def calculate_document_hash(self, content):
"""Calculate secure hash of document content"""
return hashlib.sha256(content.encode()).hexdigest()
def _is_url(self, path):
"""Check if the provided path is a URL"""
url_patterns = ['http://', 'https://', 'ftp://', 'ftps://']
return any(path.strip().lower().startswith(pattern) for pattern in url_patterns)
def _extract_from_url(self, url, verify_ssl=None):
"""Extract content from URL - download PDF temporarily and process
Args:
url: URL to download PDF from
verify_ssl: Whether to verify SSL certificates. If None, automatically
disables verification for localhost URLs
"""
import requests
import urllib3
from urllib.parse import urlparse
try:
# Determine SSL verification setting
parsed_url = urlparse(url)
hostname = parsed_url.hostname or ''
# Auto-disable SSL verification for localhost
if verify_ssl is None:
if hostname.lower() in ['localhost', '127.0.0.1', '::1']:
verify_ssl = False
print(f"Note: SSL verification disabled for localhost URL")
# Suppress only the InsecureRequestWarning for localhost
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
else:
verify_ssl = True
# Download the file from URL
print(f"Downloading document from URL: {url}")
response = requests.get(url, timeout=30, stream=True, verify=verify_ssl)
response.raise_for_status()
# Check if content type is PDF
content_type = response.headers.get('content-type', '').lower()
if 'pdf' not in content_type and not url.lower().endswith('.pdf'):
print(f"Warning: Content type is {content_type}, might not be a PDF")
# Create a temporary file to store the downloaded PDF
temp_pdf = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')
temp_pdf_path = temp_pdf.name
# Write content to temporary file
for chunk in response.iter_content(chunk_size=8192):
if chunk:
temp_pdf.write(chunk)
temp_pdf.close()
print(f"Downloaded successfully to temporary file: {temp_pdf_path}")
# Calculate document hash for audit trail
with open(temp_pdf_path, 'rb') as f:
doc_content = f.read()
doc_hash = hashlib.sha256(doc_content).hexdigest()[:16]
# Extract text and images from the downloaded file
text, images = self._extract_text_and_images(temp_pdf_path)
# Clean up temporary file after extraction
try:
os.unlink(temp_pdf_path)
print("Temporary file cleaned up")
except Exception as e:
print(f"Warning: Could not delete temporary file: {e}")
return text, images, doc_hash
except requests.exceptions.SSLError as e:
# Provide helpful error message for SSL errors
error_msg = f"SSL certificate verification failed: {e}\n"
error_msg += "For self-signed certificates, the verification is automatically disabled for localhost.\n"
error_msg += "If you're using a self-signed certificate on a non-localhost domain, "
error_msg += "consider using a trusted certificate or contact your administrator."
raise Exception(error_msg)
except requests.exceptions.RequestException as e:
raise Exception(f"Failed to download from URL: {e}")
except Exception as e:
# Clean up temp file if it exists
if 'temp_pdf_path' in locals() and os.path.exists(temp_pdf_path):
try:
os.unlink(temp_pdf_path)
except:
pass
raise e
def _prepare_document(self, pdf_path):
"""Common method to prepare document for processing (extract text/images/OCR)
Supports both file paths and URLs"""
self.check_session_timeout()
# Dynamically identify if input is URL or file path
if self._is_url(pdf_path):
# URL processing
print(f"Detected URL input: {pdf_path}")
self.hipaa_logger.log_phi_processing(self.user_id, "URL", "URL_DOWNLOAD_START")
try:
# Extract from URL
text, images, doc_hash = self._extract_from_url(pdf_path)
self.hipaa_logger.log_phi_processing(self.user_id, doc_hash, "URL_EXTRACTION")
# Perform OCR if enabled
ocr_results = []
if self.use_ocr and images:
ocr_results = self._perform_secure_ocr(images)
self.hipaa_logger.log_phi_processing(self.user_id, doc_hash, "OCR_PROCESSING")
# Analyze images if BLIP enabled
image_descriptions = []
if self.use_blip and images:
image_descriptions = self._analyze_images_securely(images)
self.hipaa_logger.log_phi_processing(self.user_id, doc_hash, "IMAGE_ANALYSIS")
# Combine all text
ocr_text = " ".join([result['ocr_text'] for result in ocr_results if result.get('ocr_text')])
combined_text = text + " " + ocr_text
return combined_text, images, ocr_results, doc_hash
except Exception as e:
self.hipaa_logger.log_access(self.user_id, "URL_PREPARATION_ERROR", pdf_path, success=False)
raise e
else:
# File path processing (existing logic)
print(f"Detected file path input: {pdf_path}")
# Calculate document hash for audit trail
with open(pdf_path, 'rb') as f:
doc_content = f.read()
doc_hash = hashlib.sha256(doc_content).hexdigest()[:16]
self.hipaa_logger.log_phi_processing(self.user_id, doc_hash, "DOCUMENT_LOAD")
try:
# Extract text and images
text, images = self._extract_text_and_images(pdf_path)
self.hipaa_logger.log_phi_processing(self.user_id, doc_hash, "TEXT_EXTRACTION")
# Perform OCR if enabled
ocr_results = []
if self.use_ocr and images:
ocr_results = self._perform_secure_ocr(images)
self.hipaa_logger.log_phi_processing(self.user_id, doc_hash, "OCR_PROCESSING")
# Analyze images if BLIP enabled
image_descriptions = []
if self.use_blip and images:
image_descriptions = self._analyze_images_securely(images)
self.hipaa_logger.log_phi_processing(self.user_id, doc_hash, "IMAGE_ANALYSIS")
# Combine all text
ocr_text = " ".join([result['ocr_text'] for result in ocr_results if result.get('ocr_text')])
combined_text = text + " " + ocr_text
return combined_text, images, ocr_results, doc_hash
except Exception as e:
self.hipaa_logger.log_access(self.user_id, "PREPARATION_ERROR", pdf_path, success=False)
raise e
def process_document_securely(self, pdf_path, questions, output_file=None):
"""Process document with full HIPAA compliance"""
combined_text, images, ocr_results, doc_hash = self._prepare_document(pdf_path)
try:
# Generate analysis
sections = self._extract_key_sections(combined_text)
key_terms = self._extract_key_terms(combined_text)
summary = self._generate_summary_secure(combined_text)
question_answers = self._answer_questions_secure(questions, combined_text)
self.hipaa_logger.log_phi_processing(self.user_id, doc_hash, "ANALYSIS_COMPLETE")
# Compile HIPAA-compliant report
report = {
"hipaa_compliance": {
"processed_locally": True,
"encrypted_storage": bool(self.secure_handler.fernet),
"audit_logged": True,
"user_id": self.user_id,
"session_id": hashlib.md5(f"{self.user_id}{self.session_start}".encode()).hexdigest()[:8],
"document_hash": doc_hash,
"processing_timestamp": datetime.now().isoformat(),
"no_external_apis": True,
"local_processing_only": True
},
"document_info": {
"file_path": os.path.basename(pdf_path), # Only filename for privacy
"analysis_timestamp": datetime.now().isoformat(),
"total_characters": len(combined_text),
"total_images": len(images),
"device_used": str(self.device)
},
"text_analysis": {
"summary": summary,
"key_terms": key_terms[:15],
"sections_found": list(sections.keys())
},
"image_analysis": {
"total_images_extracted": len(images),
"images_with_text": len([r for r in ocr_results if r.get('has_text', False)]),
"ocr_available": self.use_ocr,
"blip_available": self.use_blip
},
"question_responses": question_answers,
"statistics": {
"total_text_characters": len(combined_text),
"ocr_text_characters": len([r['ocr_text'] for r in ocr_results if r.get('ocr_text')]), # Approximate
"questions_processed": len(questions),
"sections_identified": len(sections),
"key_terms_extracted": len(key_terms)
}
}
# Save securely if output file specified
if output_file:
self.secure_handler.secure_save(report, output_file)
self.hipaa_logger.log_access(self.user_id, "REPORT_SAVE", output_file)
return report
except Exception as e:
self.hipaa_logger.log_access(self.user_id, "PROCESSING_ERROR", pdf_path, success=False)
raise e
def process_summary_only(self, pdf_path, output_file=None):
"""Process document for summary only"""
combined_text, images, ocr_results, doc_hash = self._prepare_document(pdf_path)
try:
# Generate summary
summary = self._generate_summary_secure(combined_text)
key_terms = self._extract_key_terms(combined_text)
sections = self._extract_key_sections(combined_text)
self.hipaa_logger.log_phi_processing(self.user_id, doc_hash, "SUMMARY_COMPLETE")
report = {
"hipaa_compliance": {
"processed_locally": True,
"user_id": self.user_id,
"document_hash": doc_hash,
"processing_timestamp": datetime.now().isoformat()
},
"text_analysis": {
"summary": summary,
"key_terms": key_terms[:15],
"sections_found": list(sections.keys())
}
}
if output_file:
self.secure_handler.secure_save(report, output_file)
return report
except Exception as e:
self.hipaa_logger.log_access(self.user_id, "SUMMARY_ERROR", pdf_path, success=False)
raise e
def process_summary_only_from_text(self, text_content, output_file=None):
"""Process text content for summary only (no file extraction)"""
try:
# Generate summary
summary = self._generate_summary_secure(text_content)
key_terms = self._extract_key_terms(text_content)
sections = self._extract_key_sections(text_content)
doc_hash = self.calculate_document_hash(text_content)
self.hipaa_logger.log_phi_processing(self.user_id, doc_hash, "SUMMARY_COMPLETE")
report = {
"hipaa_compliance": {
"processed_locally": True,
"user_id": self.user_id,
"document_hash": doc_hash,
"processing_timestamp": datetime.now().isoformat()
},
"text_analysis": {
"summary": summary,
"key_terms": key_terms[:15],
"sections_found": list(sections.keys())
}
}
if output_file:
self.secure_handler.secure_save(report, output_file)
return report
except Exception as e:
self.hipaa_logger.log_access(self.user_id, "SUMMARY_ERROR", "DB_CONTENT", success=False)
print(f"Error in process_summary_only_from_text: {e}")
raise e
def process_questions_only(self, pdf_path, questions, output_file=None):
"""Process document for Q&A only"""
combined_text, images, ocr_results, doc_hash = self._prepare_document(pdf_path)
try:
# Generate answers
question_answers = self._answer_questions_secure(questions, combined_text)
self.hipaa_logger.log_phi_processing(self.user_id, doc_hash, "QA_COMPLETE")
report = {
"hipaa_compliance": {
"processed_locally": True,
"user_id": self.user_id,
"document_hash": doc_hash,
"processing_timestamp": datetime.now().isoformat()
},
"question_responses": question_answers
}
if output_file:
self.secure_handler.secure_save(report, output_file)
return report
except Exception as e:
self.hipaa_logger.log_access(self.user_id, "QA_ERROR", pdf_path, success=False)
raise e
def process_questions_only_from_text(self, text_content, questions, output_file=None):
"""Process text content for Q&A only (no file extraction)"""
try:
# Generate answers
question_answers = self._answer_questions_secure(questions, text_content)
doc_hash = self.calculate_document_hash(text_content)
self.hipaa_logger.log_phi_processing(self.user_id, doc_hash, "QA_COMPLETE")
report = {
"hipaa_compliance": {
"processed_locally": True,
"user_id": self.user_id,
"document_hash": doc_hash,
"processing_timestamp": datetime.now().isoformat()
},
"question_responses": question_answers
}
if output_file:
self.secure_handler.secure_save(report, output_file)
return report
except Exception as e:
self.hipaa_logger.log_access(self.user_id, "QA_ERROR", "DB_CONTENT", success=False)
print(f"Error in process_questions_only_from_text: {e}")
raise e
def process_annotations_only(self, pdf_path, output_file=None):
"""Process document for PubTator annotations only"""
combined_text, images, ocr_results, doc_hash = self._prepare_document(pdf_path)
try:
# Initialize PubTator Annotator
# Note: PubTator legacy API might have issues, but we integrate as requested
# Using 'Gene' as a valid concept example, though API might still error
annotator = PubTatorAnnotator(bioconcept="Gene", output_format="JSON")
print("Submitting text to PubTator for annotation...")
annotations = annotator.annotate_text(combined_text)
self.hipaa_logger.log_phi_processing(self.user_id, doc_hash, "ANNOTATION_COMPLETE")
report = {
"hipaa_compliance": {
"processed_locally": False, # PubTator is external
"user_id": self.user_id,
"document_hash": doc_hash,
"processing_timestamp": datetime.now().isoformat(),
"external_api_used": "PubTator Legacy"
},
"annotations": annotations if annotations is not None else "Failed to retrieve annotations"
}
if output_file:
self.secure_handler.secure_save(report, output_file)
return report
except Exception as e:
self.hipaa_logger.log_access(self.user_id, "ANNOTATION_ERROR", pdf_path, success=False)
raise e
def save_to_database(self, pdf_path, pdf_upload_id):
"""Extract text from PDF and update existing record in PostgreSQL database"""
if not pdf_upload_id:
raise ValueError("pdf_upload_id is required for database update")
combined_text, images, ocr_results, doc_hash = self._prepare_document(pdf_path)
db_config = {
"host": os.getenv("DB_HOST", "localhost"),
"database": os.getenv("DB_NAME", "Scholarly"),
"user": os.getenv("DB_USER", "postgres"),
"password": os.getenv("DB_PASSWORD", "admin")
}
conn = None
try:
# Connect to the database
conn = psycopg2.connect(**db_config)
cur = conn.cursor()
# Update the content of the existing record
update_query = """
UPDATE tbl_pdf_uploads
SET content = %s
WHERE id = %s
RETURNING id;
"""
cur.execute(update_query, (combined_text, pdf_upload_id))
# Check if any row was updated
row = cur.fetchone()
if not row:
raise Exception(f"No record found with id {pdf_upload_id}")
updated_id = row[0]
conn.commit()
self.hipaa_logger.log_access(self.user_id, "DB_UPDATE", pdf_path)
print(f"Document content updated in database. ID: {updated_id}")
return {
"status": "success",
"message": "Content updated in database",
"db_id": updated_id,
"document_hash": doc_hash
}
except psycopg2.Error as e:
if conn:
conn.rollback()
self.hipaa_logger.log_access(self.user_id, "DB_UPDATE_ERROR", pdf_path, success=False)
print(f"Database error: {e}")
raise e
except Exception as e:
print(f"Error updating database: {e}")
raise e
finally:
if conn:
conn.close()
def _extract_text_and_images(self, pdf_path):
"""Securely extract text and images from PDF"""
text = ""
images = []
try:
# Use PyMuPDF for comprehensive extraction
doc = fitz.open(pdf_path)
for page_num in range(len(doc)):
page = doc.load_page(page_num)
# Extract text
page_text = page.get_text()
if page_text.strip():
text += page_text + "\n"
# Extract images
image_list = page.get_images()
for img_index, img in enumerate(image_list):
try:
xref = img[0]
pix = fitz.Pixmap(doc, xref)
if pix.n - pix.alpha < 4:
img_data = pix.tobytes("ppm")
img_pil = Image.open(io.BytesIO(img_data))
image_info = {
'page': page_num + 1,
'index': img_index,
'image': img_pil,
'size': img_pil.size,
'format': img_pil.format or 'Unknown'
}
images.append(image_info)
pix = None
except Exception as e:
print(f"Error extracting image {img_index} from page {page_num + 1}: {e}")
continue
doc.close()
except Exception as e:
print(f"Error in secure extraction: {e}")
return text, images
def _perform_secure_ocr(self, images):
"""Perform OCR with audit logging"""
ocr_results = []
for i, img_info in enumerate(images):
try:
img = img_info['image']
if img.mode != 'RGB':
img = img.convert('RGB')
# Preprocess for OCR
if OPENCV_AVAILABLE:
img_array = np.array(img)
gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
denoised = cv2.medianBlur(gray, 3)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
enhanced = clahe.apply(denoised)
_, thresh = cv2.threshold(enhanced, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
processed_img = Image.fromarray(thresh)
else:
gray = img.convert('L')
enhancer = ImageEnhance.Contrast(gray)
enhanced = enhancer.enhance(2.0)
processed_img = enhanced.filter(ImageFilter.SHARPEN)
# Perform OCR locally
ocr_text = pytesseract.image_to_string(processed_img, config='--psm 6')
ocr_result = {
'page': img_info['page'],
'image_index': img_info['index'],
'ocr_text': ocr_text.strip(),
'has_text': bool(ocr_text.strip()),
'processing_method': 'Local_OCR'
}
ocr_results.append(ocr_result)
except Exception as e:
ocr_results.append({
'page': img_info['page'],
'image_index': img_info['index'],
'ocr_text': '',
'has_text': False,
'error': str(e)
})
return ocr_results
def _analyze_images_securely(self, images):
"""Analyze images locally with BLIP"""
if not self.use_blip:
return []
descriptions = []
for img_info in images:
try:
image = img_info['image']
if image.mode != 'RGB':
image = image.convert('RGB')
inputs = self.blip_processor(image, return_tensors="pt").to(self.device)
with torch.no_grad():
out = self.blip_model.generate(**inputs, max_length=100, num_beams=5)
caption = self.blip_processor.decode(out[0], skip_special_tokens=True)
description = {
'page': img_info['page'],
'image_index': img_info['index'],
'caption': caption,
'processing_method': 'Local_BLIP'
}
descriptions.append(description)
except Exception as e:
descriptions.append({
'page': img_info['page'],
'image_index': img_info['index'],
'caption': 'Analysis failed',
'error': str(e)
})
return descriptions
def _extract_key_sections(self, text):
"""Extract key sections from text"""
sections = {}
section_patterns = {
'abstract': r'abstract\s*:?\s*(.*?)(?=\n\s*(?:introduction|chapter|acknowledgment|table of contents))',
'introduction': r'introduction\s*:?\s*(.*?)(?=\n\s*(?:literature review|methodology|chapter|background))',
'methodology': r'(?:methodology|methods)\s*:?\s*(.*?)(?=\n\s*(?:results|findings|analysis|chapter))',
'results': r'(?:results|findings)\s*:?\s*(.*?)(?=\n\s*(?:discussion|conclusion|chapter))',
'conclusion': r'conclusion\s*:?\s*(.*?)(?=\n\s*(?:references|bibliography|appendix))'
}
for section_name, pattern in section_patterns.items():
match = re.search(pattern, text.lower(), re.DOTALL | re.IGNORECASE)
if match:
sections[section_name] = match.group(1).strip()[:1000] # Truncate for privacy
return sections
def _extract_key_terms(self, text):
"""Extract key terms securely"""
try:
words = re.findall(r'\b[a-zA-Z]+\b', text.lower())
# Handle case where lemmatizer might be None
if self.lemmatizer is not None:
words = [
self.lemmatizer.lemmatize(word)
for word in words
if word not in self.stop_words
and len(word) > 3
and word.isalpha()
]
else:
# Fallback without lemmatization
words = [
word
for word in words
if word not in self.stop_words
and len(word) > 3
and word.isalpha()
]
word_freq = Counter(words)
return [term for term, freq in word_freq.most_common(20)]
except Exception as e:
print(f"Error in key term extraction: {e}")
return []
def _generate_summary_secure(self, text):
"""Generate summary using local T5 model"""
try:
if self.summarizer is None:
print("Summarizer not available, using fallback method")
# Fallback to extractive summary
sentences = re.split(r'[.!?]+', text)
return " ".join(sentences[:3]) + "..."
clean_text = re.sub(r'\s+', ' ', text).strip()
# Chunk text for processing
max_length = 1000
if len(clean_text) > max_length:
clean_text = clean_text[:max_length]
summary = self.summarizer(
clean_text,
max_length=200,
min_length=150,
do_sample=True,
temperature=0.7
)
return summary[0]['summary_text']
except Exception as e:
print(f"Error in T5 summarization: {e}")
# Fallback to extractive summary
sentences = re.split(r'[.!?]+', text)
return " ".join(sentences[:3]) + "..."
def _answer_questions_secure(self, questions, text):
"""Answer questions using local T5 model"""
answers = {}
for question in questions:
try:
if self.qa_pipeline is None:
answers[question] = {
'answer': 'Q&A pipeline not available - using fallback',
'method': 'Fallback',
'processed_securely': True
}
continue
prompt = f"question: {question} context: {text[:1000]}"
answer_result = self.qa_pipeline(
prompt,
max_length=200,
min_length=30,
do_sample=True,
temperature=0.7,
num_return_sequences=1
)
answer = answer_result[0]['generated_text']
answer = re.sub(r'^(answer:|Answer:)', '', answer).strip()
answers[question] = {
'answer': answer,
'method': 'Local_T5',
'processed_securely': True
}
except Exception as e:
answers[question] = {
'answer': 'Unable to process question securely',
'error': str(e),
'method': 'Error'
}
return answers
def get_annotation(self, sample_text, sample_context):
"""Generate annotations using biomed_annotator"""
try:
return generate_annotations(
selected_text=sample_text,
context_text=sample_context
)
except Exception as e:
print(f"Error in get_annotation: {e}")
self.hipaa_logger.log_access(self.user_id, "ANNOTATION_ERROR", "TEXT_SELECTION", success=False)
return []
def cleanup_session(self):
"""Clean up session data securely"""
self.hipaa_logger.log_access(self.user_id, "SESSION_END", "THESIS_ANALYZER")
# Clear sensitive data from memory
self.thesis_text = ""
self.extracted_images = []
self.ocr_results = []
self.image_descriptions = []
# Clear model cache if needed
if hasattr(torch.cuda, 'empty_cache'):
torch.cuda.empty_cache()
print("Session cleaned up securely")
class AnalyzeReq(BaseModel):
storageKey: str # path to PDF on disk (or adjust to your storage scheme)
projectId: Optional[str] = None
documentId: Optional[str] = None
ocr: bool = False
blip: bool = False
userId:str
password:str
useEncryption: bool =False
model_name: Optional[str] = "t5-small"
@app.post('/get_summary')
def get_summary(req: AnalyzeReq):
"""Get summary only"""
try:
analyzer = HIPAACompliantThesisAnalyzer(
user_id=req.userId,
password=req.password,
session_timeout=30,
model_name=req.model_name
)
report = analyzer.process_summary_only(
pdf_path=req.storageKey,
output_file="hipaa_summary_only"
)
analyzer.cleanup_session()
return report
except Exception as e:
print(f"Error in get_summary: {e}")
return {"error": str(e)}
@app.post('/get_answer')
def get_answer(req: AnalyzeReq):
"""Get answers only"""
try:
analyzer = HIPAACompliantThesisAnalyzer(
user_id=req.userId,
password=req.password,
session_timeout=30,
model_name=req.model_name
)
# Use questions from separate file
questions = THESIS_QUESTIONS
report = analyzer.process_questions_only(
pdf_path=req.storageKey,
questions=questions,
output_file="hipaa_answers_only"
)
analyzer.cleanup_session()
return report
except Exception as e:
print(f"Error in get_answer: {e}")
return {"error": str(e)}
@app.post('/upload_db')
async def upload_db(upload_db: str = Form(...), pdf_file: UploadFile = File(...)):
"""Read PDF, extract text & images + OCR, and save content to database"""
if not PSYCOPG2_AVAILABLE:
return {"error": "Database features are not available. Please install psycopg2."}
conn = None
try:
# 1. Extract content (Text + Images)
text_content = ""
ocr_text_content = ""
combined_text = ""
try:
# Read stream from UploadFile
pdf_stream = await pdf_file.read()
# Use PyMuPDF with the stream
doc = fitz.open(stream=pdf_stream, filetype="pdf")
extracted_text = []
extracted_images = []
for page_num, page in enumerate(doc):
# Extract text
page_text = page.get_text()
extracted_text.append(page_text)
# Extract images
image_list = page.get_images()
for img_index, img in enumerate(image_list):
try:
xref = img[0]
pix = fitz.Pixmap(doc, xref)
# Handle CMYK / Alpha - convert if needed
if pix.n - pix.alpha < 4: # RGB or Gray
pass
else: # CMYK: convert to RGB
pix = fitz.Pixmap(fitz.csRGB, pix)
img_data = pix.tobytes("ppm")
img_pil = Image.open(io.BytesIO(img_data))
extracted_images.append({
'page': page_num + 1,
'index': img_index,
'image': img_pil
})
pix = None
except Exception as e:
print(f"Error extracting image {img_index} on page {page_num}: {e}")
text_content = "\n".join(extracted_text)
doc.close()
# 2. Perform OCR on extracted images
if extracted_images:
print(f"Performing OCR on {len(extracted_images)} images...")
for img_info in extracted_images:
try:
img = img_info['image']
if img.mode != 'RGB':
img = img.convert('RGB')
# Preprocess (using logic similar to _perform_secure_ocr)
processed_img = img
if OPENCV_AVAILABLE:
img_array = np.array(img)
gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
denoised = cv2.medianBlur(gray, 3)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
enhanced = clahe.apply(denoised)
_, thresh = cv2.threshold(enhanced, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
processed_img = Image.fromarray(thresh)
else:
gray = img.convert('L')
enhancer = ImageEnhance.Contrast(gray)
enhanced = enhancer.enhance(2.0)
processed_img = enhanced.filter(ImageFilter.SHARPEN)
# OCR
ocr_result = pytesseract.image_to_string(processed_img, config='--psm 6')
if ocr_result.strip():
ocr_text_content += f" {ocr_result.strip()}"
except Exception as e:
print(f"OCR failed for image {img_info['index']}: {e}")
# 3. Combine Text
combined_text = text_content + "\n" + ocr_text_content
# Clean up whitespace
combined_text = re.sub(r'\s+', ' ', combined_text).strip()
except Exception as e:
print(f"Error extracting PDF content: {e}")
return {"error": f"PDF extraction failed: {str(e)}"}
# Database configuration
db_config = {
"host": os.getenv("DB_HOST", "localhost"),
"database": os.getenv("DB_NAME", "Scholarly"),
"user": os.getenv("DB_USER", "postgres"),
"password": os.getenv("DB_PASSWORD", "admin")
}
# Update database
try:
conn = psycopg2.connect(**db_config)
cur = conn.cursor()
update_query = """
UPDATE tbl_pdf_uploads
SET content = %s
WHERE pdf_uploaded_id = %s
RETURNING pdf_uploaded_id;
"""
cur.execute(update_query, (combined_text, upload_db))
row = cur.fetchone()
if not row:
return {"error": f"No record found with id {upload_db}"}
updated_id = row[0]
conn.commit()
print(f"Document content updated in database. ID: {updated_id}")
return {
"status": "success",
"message": "Content updated in database",
"db_id": updated_id
}
except psycopg2.Error as e:
if conn:
conn.rollback()
print(f"Database error: {e}")
return {"error": f"Database error: {str(e)}"}
except Exception as e:
print(f"Error in upload_db: {e}")
return {"error": str(e)}
finally:
if conn:
conn.close()
class ExtractFromUrlRequest(BaseModel):
"""Request model for extracting content from a document URL"""
document_url: str
verify_ssl: Optional[bool] = None # None = auto-detect (disabled for localhost)
def extract_content_from_pdf_stream(pdf_stream: bytes) -> dict:
"""
Extract text and images with OCR from a PDF byte stream.
Args:
pdf_stream: PDF file content as bytes
Returns:
dict with text_content, ocr_text_content, combined_text, extracted_images count
"""
text_content = ""
ocr_text_content = ""
combined_text = ""
extracted_images = []
# Use PyMuPDF with the stream
doc = fitz.open(stream=pdf_stream, filetype="pdf")
extracted_text = []
for page_num, page in enumerate(doc):
# Extract text
page_text = page.get_text()
extracted_text.append(page_text)
# Extract images
image_list = page.get_images()
for img_index, img in enumerate(image_list):
try:
xref = img[0]
pix = fitz.Pixmap(doc, xref)
# Handle CMYK / Alpha - convert if needed
if pix.n - pix.alpha < 4: # RGB or Gray
pass
else: # CMYK: convert to RGB
pix = fitz.Pixmap(fitz.csRGB, pix)
img_data = pix.tobytes("ppm")
img_pil = Image.open(io.BytesIO(img_data))
extracted_images.append({
'page': page_num + 1,
'index': img_index,
'image': img_pil
})
pix = None
except Exception as e:
print(f"Error extracting image {img_index} on page {page_num}: {e}")
text_content = "\n".join(extracted_text)
doc.close()
# Perform OCR on extracted images
if extracted_images:
print(f"Performing OCR on {len(extracted_images)} images...")
for img_info in extracted_images:
try:
img = img_info['image']
if img.mode != 'RGB':
img = img.convert('RGB')
# Preprocess
processed_img = img
if OPENCV_AVAILABLE:
img_array = np.array(img)
gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
denoised = cv2.medianBlur(gray, 3)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
enhanced = clahe.apply(denoised)
_, thresh = cv2.threshold(enhanced, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
processed_img = Image.fromarray(thresh)
else:
gray = img.convert('L')
enhancer = ImageEnhance.Contrast(gray)
enhanced = enhancer.enhance(2.0)
processed_img = enhanced.filter(ImageFilter.SHARPEN)
# OCR
ocr_result = pytesseract.image_to_string(processed_img, config='--psm 6')
if ocr_result.strip():
ocr_text_content += f" {ocr_result.strip()}"
except Exception as e:
print(f"OCR failed for image {img_info['index']}: {e}")
# Combine Text
combined_text = text_content + "\n" + ocr_text_content
# Clean up whitespace
combined_text = re.sub(r'\s+', ' ', combined_text).strip()
return {
"text_content": text_content,
"ocr_text_content": ocr_text_content,
"combined_text": combined_text,
"images_count": len(extracted_images)
}
def download_pdf_from_url(document_url: str, verify_ssl: Optional[bool] = None) -> bytes:
"""
Download PDF from URL and return as bytes.
Args:
document_url: URL to download PDF from
verify_ssl: Whether to verify SSL. None = auto-detect (disabled for localhost)
Returns:
PDF content as bytes
"""
from urllib.parse import urlparse
parsed_url = urlparse(document_url)
hostname = parsed_url.hostname or ''
# Auto-disable SSL verification for localhost
if verify_ssl is None:
if hostname.lower() in ['localhost', '127.0.0.1', '::1']:
verify_ssl = False
print(f"Note: SSL verification disabled for localhost URL")
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
else:
verify_ssl = True
# Download the file from URL
print(f"Downloading document from URL: {document_url}")
response = requests.get(document_url, timeout=30, stream=True, verify=verify_ssl)
response.raise_for_status()
# Check if content type is PDF
content_type = response.headers.get('content-type', '').lower()
if 'pdf' not in content_type and not document_url.lower().endswith('.pdf'):
print(f"Warning: Content type is {content_type}, might not be a PDF")
return response.content
@app.post('/extract_content')
async def extract_content(req: ExtractFromUrlRequest):
"""
Read PDF from URL, extract text & images + OCR, and return content.
Similar to upload_db but accepts URL instead of file and returns content instead of DB update.
"""
try:
# 1. Download the document from URL
pdf_stream = download_pdf_from_url(req.document_url, req.verify_ssl)
# 2. Extract content (Text + Images + OCR)
extraction_result = extract_content_from_pdf_stream(pdf_stream)
# 3. Calculate document hash for tracking
doc_hash = hashlib.sha256(pdf_stream).hexdigest()[:16]
print(f"Document extracted successfully from URL. Hash: {doc_hash}")
return {
"status": "success",
"message": "Content extracted from URL",
"document_hash": doc_hash,
"content": extraction_result["combined_text"],
"statistics": {
"text_length": len(extraction_result["text_content"]),
"ocr_text_length": len(extraction_result["ocr_text_content"]),
"combined_length": len(extraction_result["combined_text"]),
"images_processed": extraction_result["images_count"]
}
}
except requests.exceptions.SSLError as e:
error_msg = f"SSL certificate verification failed: {e}"
print(error_msg)
return {"error": error_msg, "hint": "For localhost, SSL verification is automatically disabled. For other domains with self-signed certs, consider using a trusted certificate."}
except requests.exceptions.RequestException as e:
print(f"Request error: {e}")
return {"error": f"Failed to download from URL: {str(e)}"}
except Exception as e:
print(f"Error in extract_from_url: {e}")
return {"error": str(e)}
@app.post('/analyze')
def analyze(req: AnalyzeReq):
"""Main function with HIPAA compliance demonstration"""
print("HIPAA-COMPLIANT THESIS ANALYZER")
print("=" * 50)
try:
# Initialize HIPAA-compliant analyzer
analyzer = HIPAACompliantThesisAnalyzer(
user_id=req.userId,
password=req.password,
session_timeout=30,
model_name=req.model_name,
mode="analyze"
)
pdf_path = req.storageKey
# Use questions from separate file
questions = THESIS_QUESTIONS
# Process document securely
print("\nProcessing document with HIPAA compliance...")
report = analyzer.process_document_securely(
pdf_path=pdf_path,
questions=questions,
output_file="hipaa_compliant_analysis"
)
print("\n" + "="*60)
print("HIPAA-COMPLIANT ANALYSIS COMPLETE")
print("="*60)
print(f"β Processed locally: {report['hipaa_compliance']['processed_locally']}")
print(f"β Encrypted storage: {report['hipaa_compliance']['encrypted_storage']}")
print(f"β Audit logged: {report['hipaa_compliance']['audit_logged']}")
print(f"β No external APIs: {report['hipaa_compliance']['no_external_apis']}")
print(f"β Session ID: {report['hipaa_compliance']['session_id']}")
# Cleanup
analyzer.cleanup_session()
return report
except Exception as e:
print(f"Error: {e}")
print("Ensure all requirements are installed and Tesseract is available.")
class AnnotationReq(BaseModel):
userId: Optional[str] = None
password: Optional[str] = None
sample_text: str
sample_context: Optional[str] = None
@app.post('/get_annotations')
def get_annotations_api(req: AnnotationReq):
"""Get annotations for selected text"""
try:
analyzer = HIPAACompliantThesisAnalyzer(
user_id=req.userId,
password=req.password,
mode="annotations"
)
annotations = analyzer.get_annotation(
sample_text=req.sample_text,
sample_context=req.sample_context
)
analyzer.cleanup_session()
return annotations
except Exception as e:
print(f"Error in get_annotations: {e}")
return {"error": str(e)}
#if __name__ == "__main__":
print("""
HIPAA-COMPLIANT THESIS ANALYZER
===============================
HIPAA COMPLIANCE FEATURES:
β Local processing only - no external API calls
β Encryption at rest with password protection
β Comprehensive audit logging
β Session timeout and access controls
β Secure file deletion
β PHI processing audit trail
β User authentication
β Data integrity verification
INSTALLATION:
pip install torch transformers PyPDF2 nltk PyMuPDF pillow pytesseract cryptography
SECURITY FEATURES:
- All processing happens locally
- Optional file encryption
- Secure memory cleanup
- Audit trail for all operations
- Session management with timeouts
- Secure file overwriting for deletion
COMPLIANCE NOTES:
- This tool provides technical safeguards
- You must implement administrative and physical safeguards
- Ensure your workstation meets HIPAA requirements
- Regular security assessments recommended
""")
#main()
|