ApsidalSolid4 commited on
Commit
721ce5e
·
verified ·
1 Parent(s): 83846c5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -249
app.py CHANGED
@@ -10,11 +10,6 @@ import gradio as gr
10
  from fastapi.middleware.cors import CORSMiddleware
11
  from concurrent.futures import ThreadPoolExecutor
12
  from functools import partial
13
- import time
14
- import csv
15
- from datetime import datetime
16
- import threading
17
- import random
18
 
19
  # Configure logging
20
  logging.basicConfig(level=logging.INFO)
@@ -29,160 +24,6 @@ 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 CSVLogger:
33
- def __init__(self, log_dir="."):
34
- """Initialize the CSV logger.
35
-
36
- Args:
37
- log_dir: Directory to store CSV log files
38
- """
39
- self.log_dir = log_dir
40
- os.makedirs(log_dir, exist_ok=True)
41
-
42
- # Create monthly CSV files
43
- current_month = datetime.now().strftime('%Y-%m')
44
- self.metrics_path = os.path.join(log_dir, f"metrics_{current_month}.csv")
45
- self.text_path = os.path.join(log_dir, f"text_data_{current_month}.csv")
46
-
47
- # Define headers
48
- self.metrics_headers = [
49
- 'entry_id', 'timestamp', 'word_count', 'mode', 'prediction',
50
- 'confidence', 'prediction_time_seconds', 'num_sentences'
51
- ]
52
-
53
- self.text_headers = ['entry_id', 'timestamp', 'text']
54
-
55
- # Initialize the files if they don't exist
56
- self._initialize_files()
57
-
58
- # Create locks for thread safety
59
- self.metrics_lock = threading.Lock()
60
- self.text_lock = threading.Lock()
61
-
62
- print(f"CSV logger initialized with files at: {os.path.abspath(self.metrics_path)}")
63
-
64
- def _initialize_files(self):
65
- """Create the CSV files with headers if they don't exist."""
66
- # Initialize metrics file
67
- if not os.path.exists(self.metrics_path):
68
- with open(self.metrics_path, 'w', newline='') as f:
69
- writer = csv.writer(f)
70
- writer.writerow(self.metrics_headers)
71
-
72
- # Initialize text data file
73
- if not os.path.exists(self.text_path):
74
- with open(self.text_path, 'w', newline='') as f:
75
- writer = csv.writer(f)
76
- writer.writerow(self.text_headers)
77
-
78
- def log_prediction(self, prediction_data, store_text=True):
79
- """Log prediction data to CSV files.
80
-
81
- Args:
82
- prediction_data: Dictionary containing prediction metrics
83
- store_text: Whether to store the full text
84
- """
85
- # Generate a unique entry ID
86
- entry_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{random.randint(1000, 9999)}"
87
-
88
- # Extract text if present
89
- text = prediction_data.pop('text', None) if store_text else None
90
-
91
- # Ensure timestamp is present
92
- if 'timestamp' not in prediction_data:
93
- prediction_data['timestamp'] = datetime.now().isoformat()
94
-
95
- # Add entry_id to metrics data
96
- metrics_data = prediction_data.copy()
97
- metrics_data['entry_id'] = entry_id
98
-
99
- # Start a thread to write data
100
- thread = threading.Thread(
101
- target=self._write_to_csv,
102
- args=(metrics_data, text, entry_id, store_text)
103
- )
104
- thread.daemon = True
105
- thread.start()
106
-
107
- def _write_to_csv(self, metrics_data, text, entry_id, store_text):
108
- """Write data to CSV files with retry mechanism."""
109
- max_retries = 5
110
- retry_delay = 0.5
111
-
112
- # Write metrics data
113
- for attempt in range(max_retries):
114
- try:
115
- with self.metrics_lock:
116
- with open(self.metrics_path, 'a', newline='') as f:
117
- writer = csv.writer(f)
118
- # Prepare row in the correct order based on headers
119
- row = [
120
- metrics_data.get('entry_id', ''),
121
- metrics_data.get('timestamp', ''),
122
- metrics_data.get('word_count', 0),
123
- metrics_data.get('mode', ''),
124
- metrics_data.get('prediction', ''),
125
- metrics_data.get('confidence', 0.0),
126
- metrics_data.get('prediction_time_seconds', 0.0),
127
- metrics_data.get('num_sentences', 0)
128
- ]
129
- writer.writerow(row)
130
- print(f"Successfully wrote metrics to CSV, entry_id: {entry_id}")
131
- break
132
- except Exception as e:
133
- print(f"Error writing metrics to CSV (attempt {attempt+1}/{max_retries}): {e}")
134
- time.sleep(retry_delay * (attempt + 1))
135
- else:
136
- # If all retries fail, write to backup file
137
- backup_path = os.path.join(self.log_dir, f"metrics_backup_{datetime.now().strftime('%Y%m%d%H%M%S')}.csv")
138
- try:
139
- with open(backup_path, 'w', newline='') as f:
140
- writer = csv.writer(f)
141
- writer.writerow(self.metrics_headers)
142
- row = [
143
- metrics_data.get('entry_id', ''),
144
- metrics_data.get('timestamp', ''),
145
- metrics_data.get('word_count', 0),
146
- metrics_data.get('mode', ''),
147
- metrics_data.get('prediction', ''),
148
- metrics_data.get('confidence', 0.0),
149
- metrics_data.get('prediction_time_seconds', 0.0),
150
- metrics_data.get('num_sentences', 0)
151
- ]
152
- writer.writerow(row)
153
- print(f"Wrote metrics backup to {backup_path}")
154
- except Exception as e:
155
- print(f"Error writing metrics backup: {e}")
156
-
157
- # Write text data if requested
158
- if store_text and text:
159
- for attempt in range(max_retries):
160
- try:
161
- with self.text_lock:
162
- with open(self.text_path, 'a', newline='') as f:
163
- writer = csv.writer(f)
164
- # Handle potential newlines in text by replacing them
165
- safe_text = text.replace('\n', ' ').replace('\r', ' ') if text else ''
166
- writer.writerow([entry_id, metrics_data.get('timestamp', ''), safe_text])
167
- print(f"Successfully wrote text data to CSV, entry_id: {entry_id}")
168
- break
169
- except Exception as e:
170
- print(f"Error writing text data to CSV (attempt {attempt+1}/{max_retries}): {e}")
171
- time.sleep(retry_delay * (attempt + 1))
172
- else:
173
- # If all retries fail, write to backup file
174
- backup_path = os.path.join(self.log_dir, f"text_backup_{datetime.now().strftime('%Y%m%d%H%M%S')}.csv")
175
- try:
176
- with open(backup_path, 'w', newline='') as f:
177
- writer = csv.writer(f)
178
- writer.writerow(self.text_headers)
179
- safe_text = text.replace('\n', ' ').replace('\r', ' ') if text else ''
180
- writer.writerow([entry_id, metrics_data.get('timestamp', ''), safe_text])
181
- print(f"Wrote text data backup to {backup_path}")
182
- except Exception as e:
183
- print(f"Error writing text data backup: {e}")
184
-
185
-
186
  class TextWindowProcessor:
187
  def __init__(self):
188
  try:
@@ -335,6 +176,100 @@ class TextClassifier:
335
  'num_windows': len(predictions)
336
  }
337
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
  def detailed_scan(self, text: str) -> Dict:
339
  """Perform a detailed scan with improved sentence-level analysis."""
340
  # Clean up trailing whitespace
@@ -485,23 +420,8 @@ class TextClassifier:
485
  'num_sentences': num_sentences
486
  }
487
 
488
- # Initialize the logger
489
- csv_logger = CSVLogger(log_dir=".")
490
-
491
- # Add file listing endpoint for debugging
492
- def list_files():
493
- """List all files in the current directory and subdirectories."""
494
- all_files = []
495
- for root, dirs, files in os.walk('.'):
496
- for file in files:
497
- all_files.append(os.path.join(root, file))
498
- return all_files
499
-
500
  def analyze_text(text: str, mode: str, classifier: TextClassifier) -> tuple:
501
  """Analyze text using specified mode and return formatted results."""
502
- # Start timing the prediction
503
- start_time = time.time()
504
-
505
  # Count words in the text
506
  word_count = len(text.split())
507
 
@@ -512,58 +432,31 @@ def analyze_text(text: str, mode: str, classifier: TextClassifier) -> tuple:
512
 
513
  if mode == "quick":
514
  result = classifier.quick_scan(text)
515
- prediction = result['prediction']
516
- confidence = result['confidence']
517
- num_windows = result['num_windows']
518
 
519
  quick_analysis = f"""
520
- PREDICTION: {prediction.upper()}
521
- Confidence: {confidence*100:.1f}%
522
- Windows analyzed: {num_windows}
523
  """
524
 
525
  # Add note if mode was switched
526
  if original_mode == "detailed":
527
  quick_analysis += f"\n\nNote: Switched to quick mode because text contains only {word_count} words. Minimum 200 words required for detailed analysis."
528
 
529
- output = (
530
  text, # No highlighting in quick mode
531
  "Quick scan mode - no sentence-level analysis available",
532
  quick_analysis
533
  )
534
-
535
- # End timing
536
- end_time = time.time()
537
- prediction_time = end_time - start_time
538
-
539
- # Log the data
540
- log_data = {
541
- "timestamp": datetime.now().isoformat(),
542
- "word_count": word_count,
543
- "mode": mode,
544
- "prediction": prediction,
545
- "confidence": confidence,
546
- "prediction_time_seconds": prediction_time,
547
- "num_sentences": 0, # No sentence analysis in quick mode
548
- "text": text
549
- }
550
-
551
- # Log to CSV
552
- print(f"Logging prediction data: word_count={word_count}, mode={mode}, prediction={prediction}")
553
- csv_logger.log_prediction(log_data)
554
-
555
  else:
556
  analysis = classifier.detailed_scan(text)
557
- prediction = analysis['overall_prediction']['prediction']
558
- confidence = analysis['overall_prediction']['confidence']
559
- num_sentences = analysis['overall_prediction']['num_sentences']
560
 
561
  detailed_analysis = []
562
  for pred in analysis['sentence_predictions']:
563
- pred_confidence = pred['confidence'] * 100
564
  detailed_analysis.append(f"Sentence: {pred['sentence']}")
565
  detailed_analysis.append(f"Prediction: {pred['prediction'].upper()}")
566
- detailed_analysis.append(f"Confidence: {pred_confidence:.1f}%")
567
  detailed_analysis.append("-" * 50)
568
 
569
  final_pred = analysis['overall_prediction']
@@ -573,33 +466,11 @@ def analyze_text(text: str, mode: str, classifier: TextClassifier) -> tuple:
573
  Number of sentences analyzed: {final_pred['num_sentences']}
574
  """
575
 
576
- output = (
577
  analysis['highlighted_text'],
578
  "\n".join(detailed_analysis),
579
  overall_result
580
  )
581
-
582
- # End timing
583
- end_time = time.time()
584
- prediction_time = end_time - start_time
585
-
586
- # Log the data
587
- log_data = {
588
- "timestamp": datetime.now().isoformat(),
589
- "word_count": word_count,
590
- "mode": mode,
591
- "prediction": prediction,
592
- "confidence": confidence,
593
- "prediction_time_seconds": prediction_time,
594
- "num_sentences": num_sentences,
595
- "text": text
596
- }
597
-
598
- # Log to CSV
599
- print(f"Logging prediction data: word_count={word_count}, mode={mode}, prediction={prediction}")
600
- csv_logger.log_prediction(log_data)
601
-
602
- return output
603
 
604
  # Initialize the classifier globally
605
  classifier = TextClassifier()
@@ -626,7 +497,7 @@ demo = gr.Interface(
626
  gr.Textbox(label="Overall Result", lines=4)
627
  ],
628
  title="AI Text Detector",
629
- 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. Note: For testing purposes, text and analysis data will be recorded.",
630
  api_name="predict",
631
  flagging_mode="never"
632
  )
@@ -640,26 +511,8 @@ app.add_middleware(
640
  allow_headers=["*"],
641
  )
642
 
643
- # Add file listing endpoint for debugging
644
- @app.get("/list_files")
645
- async def get_files():
646
- return {"files": list_files()}
647
-
648
  # Ensure CORS is applied before launching
649
  if __name__ == "__main__":
650
- # Create empty CSV files if they don't exist
651
- current_month = datetime.now().strftime('%Y-%m')
652
- metrics_path = f"metrics_{current_month}.csv"
653
- text_path = f"text_data_{current_month}.csv"
654
-
655
- print(f"Current directory: {os.getcwd()}")
656
- print(f"Looking for CSV files: {metrics_path}, {text_path}")
657
-
658
- if not os.path.exists(metrics_path):
659
- print(f"Creating metrics CSV file: {metrics_path}")
660
- if not os.path.exists(text_path):
661
- print(f"Creating text data CSV file: {text_path}")
662
-
663
  demo.queue()
664
  demo.launch(
665
  server_name="0.0.0.0",
 
10
  from fastapi.middleware.cors import CORSMiddleware
11
  from concurrent.futures import ThreadPoolExecutor
12
  from functools import partial
 
 
 
 
 
13
 
14
  # Configure logging
15
  logging.basicConfig(level=logging.INFO)
 
24
  BATCH_SIZE = 8 # Reduced batch size for CPU
25
  MAX_WORKERS = 4 # Number of worker threads for processing
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  class TextWindowProcessor:
28
  def __init__(self):
29
  try:
 
176
  'num_windows': len(predictions)
177
  }
178
 
179
+ # def detailed_scan(self, text: str) -> Dict:
180
+ # """Original prediction method with modified window handling"""
181
+ # if self.model is None or self.tokenizer is None:
182
+ # self.load_model()
183
+
184
+ # self.model.eval()
185
+ # sentences = self.processor.split_into_sentences(text)
186
+ # if not sentences:
187
+ # return {}
188
+
189
+ # # Create centered windows for each sentence
190
+ # windows, window_sentence_indices = self.processor.create_centered_windows(sentences, WINDOW_SIZE)
191
+
192
+ # # Track scores for each sentence
193
+ # sentence_appearances = {i: 0 for i in range(len(sentences))}
194
+ # sentence_scores = {i: {'human_prob': 0.0, 'ai_prob': 0.0} for i in range(len(sentences))}
195
+
196
+ # # Process windows in batches
197
+ # batch_size = 16
198
+ # for i in range(0, len(windows), batch_size):
199
+ # batch_windows = windows[i:i + batch_size]
200
+ # batch_indices = window_sentence_indices[i:i + batch_size]
201
+
202
+ # inputs = self.tokenizer(
203
+ # batch_windows,
204
+ # truncation=True,
205
+ # padding=True,
206
+ # max_length=MAX_LENGTH,
207
+ # return_tensors="pt"
208
+ # ).to(self.device)
209
+
210
+ # with torch.no_grad():
211
+ # outputs = self.model(**inputs)
212
+ # probs = F.softmax(outputs.logits, dim=-1)
213
+
214
+ # # Attribute predictions more carefully
215
+ # for window_idx, indices in enumerate(batch_indices):
216
+ # center_idx = len(indices) // 2
217
+ # center_weight = 0.7 # Higher weight for center sentence
218
+ # edge_weight = 0.3 / (len(indices) - 1) # Distribute remaining weight
219
+
220
+ # for pos, sent_idx in enumerate(indices):
221
+ # # Apply higher weight to center sentence
222
+ # weight = center_weight if pos == center_idx else edge_weight
223
+ # sentence_appearances[sent_idx] += weight
224
+ # sentence_scores[sent_idx]['human_prob'] += weight * probs[window_idx][1].item()
225
+ # sentence_scores[sent_idx]['ai_prob'] += weight * probs[window_idx][0].item()
226
+
227
+ # del inputs, outputs, probs
228
+ # if torch.cuda.is_available():
229
+ # torch.cuda.empty_cache()
230
+
231
+ # # Calculate final predictions
232
+ # sentence_predictions = []
233
+ # for i in range(len(sentences)):
234
+ # if sentence_appearances[i] > 0:
235
+ # human_prob = sentence_scores[i]['human_prob'] / sentence_appearances[i]
236
+ # ai_prob = sentence_scores[i]['ai_prob'] / sentence_appearances[i]
237
+
238
+ # # Only apply minimal smoothing at prediction boundaries
239
+ # if i > 0 and i < len(sentences) - 1:
240
+ # prev_human = sentence_scores[i-1]['human_prob'] / sentence_appearances[i-1]
241
+ # prev_ai = sentence_scores[i-1]['ai_prob'] / sentence_appearances[i-1]
242
+ # next_human = sentence_scores[i+1]['human_prob'] / sentence_appearances[i+1]
243
+ # next_ai = sentence_scores[i+1]['ai_prob'] / sentence_appearances[i+1]
244
+
245
+ # # Check if we're at a prediction boundary
246
+ # current_pred = 'human' if human_prob > ai_prob else 'ai'
247
+ # prev_pred = 'human' if prev_human > prev_ai else 'ai'
248
+ # next_pred = 'human' if next_human > next_ai else 'ai'
249
+
250
+ # if current_pred != prev_pred or current_pred != next_pred:
251
+ # # Small adjustment at boundaries
252
+ # smooth_factor = 0.1
253
+ # human_prob = (human_prob * (1 - smooth_factor) +
254
+ # (prev_human + next_human) * smooth_factor / 2)
255
+ # ai_prob = (ai_prob * (1 - smooth_factor) +
256
+ # (prev_ai + next_ai) * smooth_factor / 2)
257
+
258
+ # sentence_predictions.append({
259
+ # 'sentence': sentences[i],
260
+ # 'human_prob': human_prob,
261
+ # 'ai_prob': ai_prob,
262
+ # 'prediction': 'human' if human_prob > ai_prob else 'ai',
263
+ # 'confidence': max(human_prob, ai_prob)
264
+ # })
265
+
266
+ # return {
267
+ # 'sentence_predictions': sentence_predictions,
268
+ # 'highlighted_text': self.format_predictions_html(sentence_predictions),
269
+ # 'full_text': text,
270
+ # 'overall_prediction': self.aggregate_predictions(sentence_predictions)
271
+ # }
272
+
273
  def detailed_scan(self, text: str) -> Dict:
274
  """Perform a detailed scan with improved sentence-level analysis."""
275
  # Clean up trailing whitespace
 
420
  'num_sentences': num_sentences
421
  }
422
 
 
 
 
 
 
 
 
 
 
 
 
 
423
  def analyze_text(text: str, mode: str, classifier: TextClassifier) -> tuple:
424
  """Analyze text using specified mode and return formatted results."""
 
 
 
425
  # Count words in the text
426
  word_count = len(text.split())
427
 
 
432
 
433
  if mode == "quick":
434
  result = classifier.quick_scan(text)
 
 
 
435
 
436
  quick_analysis = f"""
437
+ PREDICTION: {result['prediction'].upper()}
438
+ Confidence: {result['confidence']*100:.1f}%
439
+ Windows analyzed: {result['num_windows']}
440
  """
441
 
442
  # Add note if mode was switched
443
  if original_mode == "detailed":
444
  quick_analysis += f"\n\nNote: Switched to quick mode because text contains only {word_count} words. Minimum 200 words required for detailed analysis."
445
 
446
+ return (
447
  text, # No highlighting in quick mode
448
  "Quick scan mode - no sentence-level analysis available",
449
  quick_analysis
450
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
451
  else:
452
  analysis = classifier.detailed_scan(text)
 
 
 
453
 
454
  detailed_analysis = []
455
  for pred in analysis['sentence_predictions']:
456
+ confidence = pred['confidence'] * 100
457
  detailed_analysis.append(f"Sentence: {pred['sentence']}")
458
  detailed_analysis.append(f"Prediction: {pred['prediction'].upper()}")
459
+ detailed_analysis.append(f"Confidence: {confidence:.1f}%")
460
  detailed_analysis.append("-" * 50)
461
 
462
  final_pred = analysis['overall_prediction']
 
466
  Number of sentences analyzed: {final_pred['num_sentences']}
467
  """
468
 
469
+ return (
470
  analysis['highlighted_text'],
471
  "\n".join(detailed_analysis),
472
  overall_result
473
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474
 
475
  # Initialize the classifier globally
476
  classifier = TextClassifier()
 
497
  gr.Textbox(label="Overall Result", lines=4)
498
  ],
499
  title="AI Text Detector",
500
+ 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.",
501
  api_name="predict",
502
  flagging_mode="never"
503
  )
 
511
  allow_headers=["*"],
512
  )
513
 
 
 
 
 
 
514
  # Ensure CORS is applied before launching
515
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
516
  demo.queue()
517
  demo.launch(
518
  server_name="0.0.0.0",