Update app.py
Browse files
app.py
CHANGED
|
@@ -18,10 +18,6 @@ from openpyxl.utils import get_column_letter
|
|
| 18 |
from io import BytesIO
|
| 19 |
import base64
|
| 20 |
import hashlib
|
| 21 |
-
import requests
|
| 22 |
-
import tempfile
|
| 23 |
-
from pathlib import Path
|
| 24 |
-
import mimetypes
|
| 25 |
|
| 26 |
# Configure logging
|
| 27 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -36,17 +32,6 @@ CONFIDENCE_THRESHOLD = 0.65
|
|
| 36 |
BATCH_SIZE = 8 # Reduced batch size for CPU
|
| 37 |
MAX_WORKERS = 4 # Number of worker threads for processing
|
| 38 |
|
| 39 |
-
# IMPORTANT: Set PyTorch thread configuration at the module level
|
| 40 |
-
# before any parallel work starts
|
| 41 |
-
if not torch.cuda.is_available():
|
| 42 |
-
# Set thread configuration only once at the beginning
|
| 43 |
-
torch.set_num_threads(MAX_WORKERS)
|
| 44 |
-
try:
|
| 45 |
-
# Only set interop threads if it hasn't been set already
|
| 46 |
-
torch.set_num_interop_threads(MAX_WORKERS)
|
| 47 |
-
except RuntimeError as e:
|
| 48 |
-
logger.warning(f"Could not set interop threads: {str(e)}")
|
| 49 |
-
|
| 50 |
# Get password hash from environment variable (more secure)
|
| 51 |
ADMIN_PASSWORD_HASH = os.environ.get('ADMIN_PASSWORD_HASH')
|
| 52 |
|
|
@@ -56,168 +41,10 @@ if not ADMIN_PASSWORD_HASH:
|
|
| 56 |
# Excel file path for logs
|
| 57 |
EXCEL_LOG_PATH = "/tmp/prediction_logs.xlsx"
|
| 58 |
|
| 59 |
-
# OCR API settings
|
| 60 |
-
OCR_API_KEY = "9e11346f1288957" # Now using the complete key
|
| 61 |
-
OCR_API_ENDPOINT = "https://api.ocr.space/parse/image"
|
| 62 |
-
OCR_MAX_PDF_PAGES = 3
|
| 63 |
-
OCR_MAX_FILE_SIZE_MB = 1
|
| 64 |
-
|
| 65 |
-
# Configure logging for OCR module
|
| 66 |
-
ocr_logger = logging.getLogger("ocr_module")
|
| 67 |
-
ocr_logger.setLevel(logging.INFO)
|
| 68 |
-
|
| 69 |
-
class OCRProcessor:
|
| 70 |
-
"""
|
| 71 |
-
Handles OCR processing of image and document files using OCR.space API
|
| 72 |
-
"""
|
| 73 |
-
def __init__(self, api_key: str = OCR_API_KEY):
|
| 74 |
-
self.api_key = api_key
|
| 75 |
-
self.endpoint = OCR_API_ENDPOINT
|
| 76 |
-
|
| 77 |
-
def process_file(self, file_path: str) -> Dict:
|
| 78 |
-
"""
|
| 79 |
-
Process a file using OCR.space API
|
| 80 |
-
"""
|
| 81 |
-
start_time = time.time()
|
| 82 |
-
ocr_logger.info(f"Starting OCR processing for file: {os.path.basename(file_path)}")
|
| 83 |
-
|
| 84 |
-
# Validate file size
|
| 85 |
-
file_size_mb = os.path.getsize(file_path) / (1024 * 1024)
|
| 86 |
-
if file_size_mb > OCR_MAX_FILE_SIZE_MB:
|
| 87 |
-
ocr_logger.warning(f"File size ({file_size_mb:.2f} MB) exceeds limit of {OCR_MAX_FILE_SIZE_MB} MB")
|
| 88 |
-
return {
|
| 89 |
-
"success": False,
|
| 90 |
-
"error": f"File size ({file_size_mb:.2f} MB) exceeds limit of {OCR_MAX_FILE_SIZE_MB} MB",
|
| 91 |
-
"text": ""
|
| 92 |
-
}
|
| 93 |
-
|
| 94 |
-
# Determine file type and handle accordingly
|
| 95 |
-
file_type = self._get_file_type(file_path)
|
| 96 |
-
ocr_logger.info(f"Detected file type: {file_type}")
|
| 97 |
-
|
| 98 |
-
# Set up API parameters
|
| 99 |
-
payload = {
|
| 100 |
-
'isOverlayRequired': 'false',
|
| 101 |
-
'language': 'eng',
|
| 102 |
-
'OCREngine': '2', # Use more accurate engine
|
| 103 |
-
'scale': 'true',
|
| 104 |
-
'detectOrientation': 'true',
|
| 105 |
-
}
|
| 106 |
-
|
| 107 |
-
# For PDF files, check page count limitations
|
| 108 |
-
if file_type == 'application/pdf':
|
| 109 |
-
ocr_logger.info("PDF document detected, enforcing page limit")
|
| 110 |
-
payload['filetype'] = 'PDF'
|
| 111 |
-
|
| 112 |
-
# Prepare file for OCR API - using file data as bytes to avoid file handle issues
|
| 113 |
-
with open(file_path, 'rb') as f:
|
| 114 |
-
file_data = f.read()
|
| 115 |
-
|
| 116 |
-
files = {
|
| 117 |
-
'file': (os.path.basename(file_path), file_data, file_type)
|
| 118 |
-
}
|
| 119 |
-
|
| 120 |
-
headers = {
|
| 121 |
-
'apikey': self.api_key,
|
| 122 |
-
}
|
| 123 |
-
|
| 124 |
-
# Make the OCR API request
|
| 125 |
-
try:
|
| 126 |
-
ocr_logger.info(f"Sending request to OCR.space API for file: {os.path.basename(file_path)}")
|
| 127 |
-
response = requests.post(
|
| 128 |
-
self.endpoint,
|
| 129 |
-
files=files,
|
| 130 |
-
data=payload,
|
| 131 |
-
headers=headers,
|
| 132 |
-
timeout=60 # Add 60 second timeout
|
| 133 |
-
)
|
| 134 |
-
|
| 135 |
-
ocr_logger.info(f"OCR API status code: {response.status_code}")
|
| 136 |
-
|
| 137 |
-
# Log response text for debugging (first 200 chars)
|
| 138 |
-
response_preview = response.text[:200] if hasattr(response, 'text') else "No text content"
|
| 139 |
-
ocr_logger.info(f"OCR API response preview: {response_preview}...")
|
| 140 |
-
|
| 141 |
-
try:
|
| 142 |
-
response.raise_for_status()
|
| 143 |
-
except Exception as e:
|
| 144 |
-
ocr_logger.error(f"HTTP Error: {str(e)}")
|
| 145 |
-
return {
|
| 146 |
-
"success": False,
|
| 147 |
-
"error": f"OCR API HTTP Error: {str(e)}",
|
| 148 |
-
"text": ""
|
| 149 |
-
}
|
| 150 |
-
|
| 151 |
-
try:
|
| 152 |
-
result = response.json()
|
| 153 |
-
ocr_logger.info(f"OCR API exit code: {result.get('OCRExitCode')}")
|
| 154 |
-
|
| 155 |
-
# Process the OCR results
|
| 156 |
-
if result.get('OCRExitCode') in [1, 2]: # Success or partial success
|
| 157 |
-
extracted_text = self._extract_text_from_result(result)
|
| 158 |
-
processing_time = time.time() - start_time
|
| 159 |
-
ocr_logger.info(f"OCR processing completed in {processing_time:.2f} seconds")
|
| 160 |
-
ocr_logger.info(f"Extracted text word count: {len(extracted_text.split())}")
|
| 161 |
-
|
| 162 |
-
return {
|
| 163 |
-
"success": True,
|
| 164 |
-
"text": extracted_text,
|
| 165 |
-
"word_count": len(extracted_text.split()),
|
| 166 |
-
"processing_time_ms": int(processing_time * 1000)
|
| 167 |
-
}
|
| 168 |
-
else:
|
| 169 |
-
error_msg = result.get('ErrorMessage', 'OCR processing failed')
|
| 170 |
-
ocr_logger.error(f"OCR API error: {error_msg}")
|
| 171 |
-
return {
|
| 172 |
-
"success": False,
|
| 173 |
-
"error": error_msg,
|
| 174 |
-
"text": ""
|
| 175 |
-
}
|
| 176 |
-
except ValueError as e:
|
| 177 |
-
ocr_logger.error(f"Invalid JSON response: {str(e)}")
|
| 178 |
-
return {
|
| 179 |
-
"success": False,
|
| 180 |
-
"error": f"Invalid response from OCR API: {str(e)}",
|
| 181 |
-
"text": ""
|
| 182 |
-
}
|
| 183 |
-
|
| 184 |
-
except requests.exceptions.RequestException as e:
|
| 185 |
-
ocr_logger.error(f"OCR API request failed: {str(e)}")
|
| 186 |
-
return {
|
| 187 |
-
"success": False,
|
| 188 |
-
"error": f"OCR API request failed: {str(e)}",
|
| 189 |
-
"text": ""
|
| 190 |
-
}
|
| 191 |
-
finally:
|
| 192 |
-
# No need to close file handle as we're using bytes directly
|
| 193 |
-
pass
|
| 194 |
-
|
| 195 |
-
def _extract_text_from_result(self, result: Dict) -> str:
|
| 196 |
-
"""
|
| 197 |
-
Extract all text from the OCR API result
|
| 198 |
-
"""
|
| 199 |
-
extracted_text = ""
|
| 200 |
-
|
| 201 |
-
if 'ParsedResults' in result and result['ParsedResults']:
|
| 202 |
-
for parsed_result in result['ParsedResults']:
|
| 203 |
-
if parsed_result.get('ParsedText'):
|
| 204 |
-
extracted_text += parsed_result['ParsedText']
|
| 205 |
-
|
| 206 |
-
return extracted_text
|
| 207 |
-
|
| 208 |
-
def _get_file_type(self, file_path: str) -> str:
|
| 209 |
-
"""
|
| 210 |
-
Determine MIME type of a file
|
| 211 |
-
"""
|
| 212 |
-
mime_type, _ = mimetypes.guess_type(file_path)
|
| 213 |
-
if mime_type is None:
|
| 214 |
-
# Default to binary if MIME type can't be determined
|
| 215 |
-
return 'application/octet-stream'
|
| 216 |
-
return mime_type
|
| 217 |
-
|
| 218 |
def is_admin_password(input_text: str) -> bool:
|
| 219 |
"""
|
| 220 |
Check if the input text matches the admin password using secure hash comparison.
|
|
|
|
| 221 |
"""
|
| 222 |
# Hash the input text
|
| 223 |
input_hash = hashlib.sha256(input_text.strip().encode()).hexdigest()
|
|
@@ -278,6 +105,11 @@ class TextWindowProcessor:
|
|
| 278 |
|
| 279 |
class TextClassifier:
|
| 280 |
def __init__(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 282 |
self.model_name = MODEL_NAME
|
| 283 |
self.tokenizer = None
|
|
@@ -421,7 +253,7 @@ class TextClassifier:
|
|
| 421 |
for window_idx, indices in enumerate(batch_indices):
|
| 422 |
center_idx = len(indices) // 2
|
| 423 |
center_weight = 0.7 # Higher weight for center sentence
|
| 424 |
-
edge_weight = 0.3 / (len(indices) - 1)
|
| 425 |
|
| 426 |
for pos, sent_idx in enumerate(indices):
|
| 427 |
# Apply higher weight to center sentence
|
|
@@ -444,10 +276,10 @@ class TextClassifier:
|
|
| 444 |
|
| 445 |
# Apply minimal smoothing at prediction boundaries
|
| 446 |
if i > 0 and i < len(sentences) - 1:
|
| 447 |
-
prev_human = sentence_scores[i-1]['human_prob'] /
|
| 448 |
-
prev_ai = sentence_scores[i-1]['ai_prob'] /
|
| 449 |
-
next_human = sentence_scores[i+1]['human_prob'] /
|
| 450 |
-
next_ai = sentence_scores[i+1]['ai_prob'] /
|
| 451 |
|
| 452 |
# Check if we're at a prediction boundary
|
| 453 |
current_pred = 'human' if human_prob > ai_prob else 'ai'
|
|
@@ -522,105 +354,6 @@ class TextClassifier:
|
|
| 522 |
'num_sentences': num_sentences
|
| 523 |
}
|
| 524 |
|
| 525 |
-
# Function to handle file upload, OCR processing, and text analysis
|
| 526 |
-
def handle_file_upload_and_analyze(file_obj, mode: str) -> tuple:
|
| 527 |
-
"""
|
| 528 |
-
Handle file upload, OCR processing, and text analysis
|
| 529 |
-
"""
|
| 530 |
-
# Use the global classifier
|
| 531 |
-
global classifier
|
| 532 |
-
classifier_to_use = classifier
|
| 533 |
-
|
| 534 |
-
if file_obj is None:
|
| 535 |
-
return (
|
| 536 |
-
"No file uploaded",
|
| 537 |
-
"Please upload a file to analyze",
|
| 538 |
-
"No file uploaded for analysis"
|
| 539 |
-
)
|
| 540 |
-
|
| 541 |
-
# Log the type of file object received
|
| 542 |
-
logger.info(f"Received file upload of type: {type(file_obj)}")
|
| 543 |
-
|
| 544 |
-
try:
|
| 545 |
-
# Create a temporary file with an appropriate extension based on content
|
| 546 |
-
if isinstance(file_obj, bytes):
|
| 547 |
-
content_start = file_obj[:20] # Look at the first few bytes
|
| 548 |
-
|
| 549 |
-
# Default to .bin extension
|
| 550 |
-
file_ext = ".bin"
|
| 551 |
-
|
| 552 |
-
# Try to detect PDF files
|
| 553 |
-
if content_start.startswith(b'%PDF'):
|
| 554 |
-
file_ext = ".pdf"
|
| 555 |
-
# For images, detect by common magic numbers
|
| 556 |
-
elif content_start.startswith(b'\xff\xd8'): # JPEG
|
| 557 |
-
file_ext = ".jpg"
|
| 558 |
-
elif content_start.startswith(b'\x89PNG'): # PNG
|
| 559 |
-
file_ext = ".png"
|
| 560 |
-
elif content_start.startswith(b'GIF'): # GIF
|
| 561 |
-
file_ext = ".gif"
|
| 562 |
-
|
| 563 |
-
# Create a temporary file with the detected extension
|
| 564 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=file_ext) as temp_file:
|
| 565 |
-
temp_file_path = temp_file.name
|
| 566 |
-
# Write uploaded file data to the temporary file
|
| 567 |
-
temp_file.write(file_obj)
|
| 568 |
-
logger.info(f"Saved uploaded file to {temp_file_path}")
|
| 569 |
-
else:
|
| 570 |
-
# Handle other file object types (should not typically happen with Gradio)
|
| 571 |
-
logger.error(f"Unexpected file object type: {type(file_obj)}")
|
| 572 |
-
return (
|
| 573 |
-
"File upload error",
|
| 574 |
-
"Unexpected file format",
|
| 575 |
-
"Unable to process this file format"
|
| 576 |
-
)
|
| 577 |
-
|
| 578 |
-
# Process the file with OCR
|
| 579 |
-
ocr_processor = OCRProcessor()
|
| 580 |
-
logger.info(f"Starting OCR processing for file: {temp_file_path}")
|
| 581 |
-
ocr_result = ocr_processor.process_file(temp_file_path)
|
| 582 |
-
|
| 583 |
-
if not ocr_result["success"]:
|
| 584 |
-
logger.error(f"OCR processing failed: {ocr_result['error']}")
|
| 585 |
-
return (
|
| 586 |
-
"OCR Processing Error",
|
| 587 |
-
ocr_result["error"],
|
| 588 |
-
"Failed to extract text from the uploaded file"
|
| 589 |
-
)
|
| 590 |
-
|
| 591 |
-
# Get the extracted text
|
| 592 |
-
extracted_text = ocr_result["text"]
|
| 593 |
-
logger.info(f"OCR processing complete. Extracted {len(extracted_text.split())} words")
|
| 594 |
-
|
| 595 |
-
# If no text was extracted
|
| 596 |
-
if not extracted_text.strip():
|
| 597 |
-
logger.warning("No text extracted from file")
|
| 598 |
-
return (
|
| 599 |
-
"No text extracted",
|
| 600 |
-
"The OCR process did not extract any text from the uploaded file.",
|
| 601 |
-
"No text was found in the uploaded file"
|
| 602 |
-
)
|
| 603 |
-
|
| 604 |
-
# Call the original text analysis function with the extracted text
|
| 605 |
-
logger.info("Proceeding with text analysis")
|
| 606 |
-
return analyze_text(extracted_text, mode, classifier_to_use)
|
| 607 |
-
|
| 608 |
-
except Exception as e:
|
| 609 |
-
logger.error(f"Error in file upload processing: {str(e)}")
|
| 610 |
-
return (
|
| 611 |
-
"Error Processing File",
|
| 612 |
-
f"An error occurred while processing the file: {str(e)}",
|
| 613 |
-
"File processing error. Please try again or try a different file."
|
| 614 |
-
)
|
| 615 |
-
finally:
|
| 616 |
-
# Clean up the temporary file
|
| 617 |
-
if 'temp_file_path' in locals() and os.path.exists(temp_file_path):
|
| 618 |
-
try:
|
| 619 |
-
os.remove(temp_file_path)
|
| 620 |
-
logger.info(f"Removed temporary file: {temp_file_path}")
|
| 621 |
-
except Exception as e:
|
| 622 |
-
logger.warning(f"Could not remove temporary file: {str(e)}")
|
| 623 |
-
|
| 624 |
def initialize_excel_log():
|
| 625 |
"""Initialize the Excel log file if it doesn't exist."""
|
| 626 |
if not os.path.exists(EXCEL_LOG_PATH):
|
|
@@ -648,7 +381,6 @@ def initialize_excel_log():
|
|
| 648 |
wb.save(EXCEL_LOG_PATH)
|
| 649 |
logger.info(f"Initialized Excel log file at {EXCEL_LOG_PATH}")
|
| 650 |
|
| 651 |
-
|
| 652 |
def log_prediction_data(input_text, word_count, prediction, confidence, execution_time, mode):
|
| 653 |
"""Log prediction data to an Excel file in the /tmp directory."""
|
| 654 |
# Initialize the Excel file if it doesn't exist
|
|
@@ -691,7 +423,6 @@ def log_prediction_data(input_text, word_count, prediction, confidence, executio
|
|
| 691 |
logger.error(f"Error logging prediction data to Excel: {str(e)}")
|
| 692 |
return False
|
| 693 |
|
| 694 |
-
|
| 695 |
def get_logs_as_base64():
|
| 696 |
"""Read the Excel logs file and return as base64 for downloading."""
|
| 697 |
if not os.path.exists(EXCEL_LOG_PATH):
|
|
@@ -710,7 +441,6 @@ def get_logs_as_base64():
|
|
| 710 |
logger.error(f"Error reading Excel logs: {str(e)}")
|
| 711 |
return None
|
| 712 |
|
| 713 |
-
|
| 714 |
def analyze_text(text: str, mode: str, classifier: TextClassifier) -> tuple:
|
| 715 |
"""Analyze text using specified mode and return formatted results."""
|
| 716 |
# Check if the input text matches the admin password using secure comparison
|
|
@@ -833,143 +563,51 @@ def analyze_text(text: str, mode: str, classifier: TextClassifier) -> tuple:
|
|
| 833 |
# Initialize the classifier globally
|
| 834 |
classifier = TextClassifier()
|
| 835 |
|
| 836 |
-
# Create Gradio interface
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
}
|
| 851 |
-
|
| 852 |
-
/* Hide file preview elements */
|
| 853 |
-
.file-upload .file-preview,
|
| 854 |
-
.file-upload p:not(.file-upload p:first-child),
|
| 855 |
-
.file-upload svg,
|
| 856 |
-
.file-upload [data-testid="chunkFileDropArea"],
|
| 857 |
-
.file-upload .file-drop {
|
| 858 |
-
display: none !important;
|
| 859 |
-
}
|
| 860 |
-
|
| 861 |
-
/* Style the upload button */
|
| 862 |
-
.file-upload button {
|
| 863 |
-
height: 40px !important;
|
| 864 |
-
width: 100% !important;
|
| 865 |
-
background-color: #f0f0f0 !important;
|
| 866 |
-
border: 1px solid #d9d9d9 !important;
|
| 867 |
-
border-radius: 4px !important;
|
| 868 |
-
color: #333 !important;
|
| 869 |
-
font-size: 14px !important;
|
| 870 |
-
display: flex !important;
|
| 871 |
-
align-items: center !important;
|
| 872 |
-
justify-content: center !important;
|
| 873 |
-
margin: 0 !important;
|
| 874 |
-
padding: 0 !important;
|
| 875 |
-
}
|
| 876 |
-
|
| 877 |
-
/* Hide the "or" text */
|
| 878 |
-
.file-upload .or {
|
| 879 |
-
display: none !important;
|
| 880 |
-
}
|
| 881 |
-
|
| 882 |
-
/* Make the container compact */
|
| 883 |
-
.file-upload [data-testid="block"] {
|
| 884 |
-
margin: 0 !important;
|
| 885 |
-
padding: 0 !important;
|
| 886 |
-
}
|
| 887 |
-
"""
|
| 888 |
-
|
| 889 |
-
with gr.Blocks(css=css, title="AI Text Detector") as demo:
|
| 890 |
-
gr.Markdown("# AI Text Detector")
|
| 891 |
-
gr.Markdown("Analyze text to detect if it was written by a human or AI. Choose between quick scan and detailed sentence-level analysis. 200+ words suggested for accurate predictions.")
|
| 892 |
-
|
| 893 |
-
with gr.Row():
|
| 894 |
-
# Left column - Input
|
| 895 |
-
with gr.Column(scale=1):
|
| 896 |
-
# Text input area
|
| 897 |
-
text_input = gr.Textbox(
|
| 898 |
-
lines=8,
|
| 899 |
-
placeholder="Enter text to analyze...",
|
| 900 |
-
label="Input Text"
|
| 901 |
-
)
|
| 902 |
-
|
| 903 |
-
# Analysis Mode section
|
| 904 |
-
gr.Markdown("Analysis Mode")
|
| 905 |
-
gr.Markdown("Quick mode for faster analysis. Detailed mode for sentence-level analysis.")
|
| 906 |
-
|
| 907 |
-
# Simple row layout for radio buttons and file upload
|
| 908 |
-
with gr.Row():
|
| 909 |
-
mode_selection = gr.Radio(
|
| 910 |
-
choices=["quick", "detailed"],
|
| 911 |
-
value="quick",
|
| 912 |
-
label="",
|
| 913 |
-
show_label=False
|
| 914 |
-
)
|
| 915 |
-
|
| 916 |
-
# Revert to File component but with better styling
|
| 917 |
-
file_upload = gr.File(
|
| 918 |
-
file_types=["image", "pdf", "doc", "docx"],
|
| 919 |
-
elem_classes=["file-upload"]
|
| 920 |
-
)
|
| 921 |
-
|
| 922 |
-
# Analyze button
|
| 923 |
-
analyze_btn = gr.Button("Analyze Text", elem_id="analyze-btn")
|
| 924 |
-
|
| 925 |
-
# Right column - Results
|
| 926 |
-
with gr.Column(scale=1):
|
| 927 |
-
output_html = gr.HTML(label="Highlighted Analysis")
|
| 928 |
-
output_sentences = gr.Textbox(label="Sentence-by-Sentence Analysis", lines=10)
|
| 929 |
-
output_result = gr.Textbox(label="Overall Result", lines=4)
|
| 930 |
-
|
| 931 |
-
# Connect components
|
| 932 |
-
analyze_btn.click(
|
| 933 |
-
fn=lambda text, mode: analyze_text(text, mode, classifier),
|
| 934 |
-
inputs=[text_input, mode_selection],
|
| 935 |
-
outputs=[output_html, output_sentences, output_result]
|
| 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 |
-
return demo
|
| 964 |
-
|
| 965 |
-
# Initialize the application
|
| 966 |
if __name__ == "__main__":
|
| 967 |
-
demo = setup_app()
|
| 968 |
-
|
| 969 |
-
# Start the server
|
| 970 |
demo.queue()
|
| 971 |
demo.launch(
|
| 972 |
server_name="0.0.0.0",
|
| 973 |
server_port=7860,
|
| 974 |
share=True
|
| 975 |
-
)
|
|
|
|
|
|
| 18 |
from io import BytesIO
|
| 19 |
import base64
|
| 20 |
import hashlib
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
# Configure logging
|
| 23 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 32 |
BATCH_SIZE = 8 # Reduced batch size for CPU
|
| 33 |
MAX_WORKERS = 4 # Number of worker threads for processing
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
# Get password hash from environment variable (more secure)
|
| 36 |
ADMIN_PASSWORD_HASH = os.environ.get('ADMIN_PASSWORD_HASH')
|
| 37 |
|
|
|
|
| 41 |
# Excel file path for logs
|
| 42 |
EXCEL_LOG_PATH = "/tmp/prediction_logs.xlsx"
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
def is_admin_password(input_text: str) -> bool:
|
| 45 |
"""
|
| 46 |
Check if the input text matches the admin password using secure hash comparison.
|
| 47 |
+
This prevents the password from being visible in the source code.
|
| 48 |
"""
|
| 49 |
# Hash the input text
|
| 50 |
input_hash = hashlib.sha256(input_text.strip().encode()).hexdigest()
|
|
|
|
| 105 |
|
| 106 |
class TextClassifier:
|
| 107 |
def __init__(self):
|
| 108 |
+
# Set thread configuration before any model loading or parallel work
|
| 109 |
+
if not torch.cuda.is_available():
|
| 110 |
+
torch.set_num_threads(MAX_WORKERS)
|
| 111 |
+
torch.set_num_interop_threads(MAX_WORKERS)
|
| 112 |
+
|
| 113 |
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 114 |
self.model_name = MODEL_NAME
|
| 115 |
self.tokenizer = None
|
|
|
|
| 253 |
for window_idx, indices in enumerate(batch_indices):
|
| 254 |
center_idx = len(indices) // 2
|
| 255 |
center_weight = 0.7 # Higher weight for center sentence
|
| 256 |
+
edge_weight = 0.3 / (len(indices) - 1) # Distribute remaining weight
|
| 257 |
|
| 258 |
for pos, sent_idx in enumerate(indices):
|
| 259 |
# Apply higher weight to center sentence
|
|
|
|
| 276 |
|
| 277 |
# Apply minimal smoothing at prediction boundaries
|
| 278 |
if i > 0 and i < len(sentences) - 1:
|
| 279 |
+
prev_human = sentence_scores[i-1]['human_prob'] / sentence_appearances[i-1]
|
| 280 |
+
prev_ai = sentence_scores[i-1]['ai_prob'] / sentence_appearances[i-1]
|
| 281 |
+
next_human = sentence_scores[i+1]['human_prob'] / sentence_appearances[i+1]
|
| 282 |
+
next_ai = sentence_scores[i+1]['ai_prob'] / sentence_appearances[i+1]
|
| 283 |
|
| 284 |
# Check if we're at a prediction boundary
|
| 285 |
current_pred = 'human' if human_prob > ai_prob else 'ai'
|
|
|
|
| 354 |
'num_sentences': num_sentences
|
| 355 |
}
|
| 356 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
def initialize_excel_log():
|
| 358 |
"""Initialize the Excel log file if it doesn't exist."""
|
| 359 |
if not os.path.exists(EXCEL_LOG_PATH):
|
|
|
|
| 381 |
wb.save(EXCEL_LOG_PATH)
|
| 382 |
logger.info(f"Initialized Excel log file at {EXCEL_LOG_PATH}")
|
| 383 |
|
|
|
|
| 384 |
def log_prediction_data(input_text, word_count, prediction, confidence, execution_time, mode):
|
| 385 |
"""Log prediction data to an Excel file in the /tmp directory."""
|
| 386 |
# Initialize the Excel file if it doesn't exist
|
|
|
|
| 423 |
logger.error(f"Error logging prediction data to Excel: {str(e)}")
|
| 424 |
return False
|
| 425 |
|
|
|
|
| 426 |
def get_logs_as_base64():
|
| 427 |
"""Read the Excel logs file and return as base64 for downloading."""
|
| 428 |
if not os.path.exists(EXCEL_LOG_PATH):
|
|
|
|
| 441 |
logger.error(f"Error reading Excel logs: {str(e)}")
|
| 442 |
return None
|
| 443 |
|
|
|
|
| 444 |
def analyze_text(text: str, mode: str, classifier: TextClassifier) -> tuple:
|
| 445 |
"""Analyze text using specified mode and return formatted results."""
|
| 446 |
# Check if the input text matches the admin password using secure comparison
|
|
|
|
| 563 |
# Initialize the classifier globally
|
| 564 |
classifier = TextClassifier()
|
| 565 |
|
| 566 |
+
# Create Gradio interface
|
| 567 |
+
demo = gr.Interface(
|
| 568 |
+
fn=lambda text, mode: analyze_text(text, mode, classifier),
|
| 569 |
+
inputs=[
|
| 570 |
+
gr.Textbox(
|
| 571 |
+
lines=8,
|
| 572 |
+
placeholder="Enter text to analyze...",
|
| 573 |
+
label="Input Text"
|
| 574 |
+
),
|
| 575 |
+
gr.Radio(
|
| 576 |
+
choices=["quick", "detailed"],
|
| 577 |
+
value="quick",
|
| 578 |
+
label="Analysis Mode",
|
| 579 |
+
info="Quick mode for faster analysis, Detailed mode for sentence-level analysis"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 580 |
)
|
| 581 |
+
],
|
| 582 |
+
outputs=[
|
| 583 |
+
gr.HTML(label="Highlighted Analysis"),
|
| 584 |
+
gr.Textbox(label="Sentence-by-Sentence Analysis", lines=10),
|
| 585 |
+
gr.Textbox(label="Overall Result", lines=4)
|
| 586 |
+
],
|
| 587 |
+
title="AI Text Detector",
|
| 588 |
+
description="Analyze text to detect if it was written by a human or AI. Choose between quick scan and detailed sentence-level analysis. 200+ words suggested for accurate predictions.",
|
| 589 |
+
api_name="predict",
|
| 590 |
+
flagging_mode="never"
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
# Get the FastAPI app from Gradio
|
| 594 |
+
app = demo.app
|
| 595 |
+
|
| 596 |
+
# Add CORS middleware
|
| 597 |
+
app.add_middleware(
|
| 598 |
+
CORSMiddleware,
|
| 599 |
+
allow_origins=["*"], # For development
|
| 600 |
+
allow_credentials=True,
|
| 601 |
+
allow_methods=["GET", "POST", "OPTIONS"],
|
| 602 |
+
allow_headers=["*"],
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
# Ensure CORS is applied before launching
|
|
|
|
|
|
|
|
|
|
|
|
|
| 606 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
| 607 |
demo.queue()
|
| 608 |
demo.launch(
|
| 609 |
server_name="0.0.0.0",
|
| 610 |
server_port=7860,
|
| 611 |
share=True
|
| 612 |
+
)
|
| 613 |
+
|