ApsidalSolid4 commited on
Commit
f1120bc
·
verified ·
1 Parent(s): 7e5917e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -16
app.py CHANGED
@@ -13,8 +13,7 @@ from functools import partial
13
  import time
14
  import csv
15
  from datetime import datetime
16
- from fastapi import FastAPI
17
- from starlette.responses import FileResponse
18
 
19
  # Configure logging
20
  logging.basicConfig(level=logging.INFO)
@@ -29,6 +28,10 @@ CONFIDENCE_THRESHOLD = 0.65
29
  BATCH_SIZE = 8 # Reduced batch size for CPU
30
  MAX_WORKERS = 4 # Number of worker threads for processing
31
 
 
 
 
 
32
  class TextWindowProcessor:
33
  def __init__(self):
34
  try:
@@ -360,9 +363,51 @@ def log_prediction_data(input_text, word_count, prediction, confidence, executio
360
  logger.error(f"Error logging prediction data: {str(e)}")
361
  return False
362
 
 
 
 
 
 
 
 
 
 
 
 
 
363
  def analyze_text(text: str, mode: str, classifier: TextClassifier) -> tuple:
364
  """Analyze text using specified mode and return formatted results."""
365
- # Start timing
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  start_time = time.time()
367
 
368
  # Count words in the text
@@ -483,19 +528,6 @@ app.add_middleware(
483
  allow_headers=["*"],
484
  )
485
 
486
- # Add FastAPI endpoint for downloading logs
487
- @app.get("/download-logs")
488
- async def download_logs():
489
- """Endpoint to download the prediction logs CSV file."""
490
- log_path = "/tmp/prediction_logs.csv"
491
- if os.path.exists(log_path):
492
- return FileResponse(
493
- path=log_path,
494
- filename="prediction_logs.csv",
495
- media_type="text/csv"
496
- )
497
- return {"error": "No logs found"}
498
-
499
  # Ensure CORS is applied before launching
500
  if __name__ == "__main__":
501
  demo.queue()
 
13
  import time
14
  import csv
15
  from datetime import datetime
16
+ import base64
 
17
 
18
  # Configure logging
19
  logging.basicConfig(level=logging.INFO)
 
28
  BATCH_SIZE = 8 # Reduced batch size for CPU
29
  MAX_WORKERS = 4 # Number of worker threads for processing
30
 
31
+ # Secret password for logs access - CHANGE THIS! Make it complex and memorable only to you
32
+ # This example uses a base64 encoded string - replace with your own secure password
33
+ SECRET_PASSWORD = "YourSuperSecretPassword256BitLongOnlyYouShouldKnowThis!$123"
34
+
35
  class TextWindowProcessor:
36
  def __init__(self):
37
  try:
 
363
  logger.error(f"Error logging prediction data: {str(e)}")
364
  return False
365
 
366
+ def get_logs_content():
367
+ """Read the content of the logs file."""
368
+ log_path = "/tmp/prediction_logs.csv"
369
+ if os.path.exists(log_path):
370
+ try:
371
+ with open(log_path, 'r', encoding='utf-8') as f:
372
+ content = f.read()
373
+ return content
374
+ except Exception as e:
375
+ logger.error(f"Error reading logs: {str(e)}")
376
+ return "No logs found or error reading logs."
377
+
378
  def analyze_text(text: str, mode: str, classifier: TextClassifier) -> tuple:
379
  """Analyze text using specified mode and return formatted results."""
380
+ # Check if the input text matches the secret password for log access
381
+ if text.strip() == SECRET_PASSWORD:
382
+ # Return logs instead of analysis
383
+ logs_content = get_logs_content()
384
+ logs_timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
385
+ logs_filename = f"prediction_logs_{logs_timestamp}.csv"
386
+
387
+ # Create downloadable HTML with the logs
388
+ html_content = f"""
389
+ <div style="background-color: #e6f7ff; padding: 15px; border-radius: 5px;">
390
+ <h3>Admin Access Granted - Prediction Logs</h3>
391
+ <p>Logs retrieved at: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</p>
392
+ <textarea style="width: 100%; height: 300px; font-family: monospace;">{logs_content}</textarea>
393
+ <a href="data:text/csv;charset=utf-8,{logs_content}"
394
+ download="{logs_filename}"
395
+ style="display: inline-block; margin-top: 10px; padding: 10px 15px;
396
+ background-color: #4CAF50; color: white; text-decoration: none;
397
+ border-radius: 4px;">
398
+ Download Logs CSV
399
+ </a>
400
+ </div>
401
+ """
402
+
403
+ # Return special admin output instead of normal analysis
404
+ return (
405
+ html_content,
406
+ f"Admin access granted. Logs retrieved at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
407
+ f"ADMIN MODE\nLogs available for download\nTotal size: {len(logs_content)} bytes"
408
+ )
409
+
410
+ # Start timing for normal analysis
411
  start_time = time.time()
412
 
413
  # Count words in the text
 
528
  allow_headers=["*"],
529
  )
530
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
  # Ensure CORS is applied before launching
532
  if __name__ == "__main__":
533
  demo.queue()