VictorM-Coder commited on
Commit
a35760f
Β·
verified Β·
1 Parent(s): 5030a83

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -26
app.py CHANGED
@@ -69,19 +69,20 @@ def split_preserving_structure(text):
69
  def analyze(text):
70
  if not text.strip():
71
  return "β€”", "β€”", "<em>Please enter text...</em>", None
72
-
73
  try:
74
  tok, mod = get_model()
75
  except Exception as e:
76
  return "ERROR", "0%", f"Failed to load model: {str(e)}", None
77
 
78
  blocks = split_preserving_structure(text)
79
- pure_sents = [b for b in blocks if b.strip() and not b.startswith("\n")]
80
-
 
 
81
  if not pure_sents:
82
  return "β€”", "β€”", "<em>No sentences detected.</em>", None
83
 
84
- # Sliding Window (Size 3, Stride 1) - Much more accurate than hard chunks
85
  windows = []
86
  for i in range(len(pure_sents)):
87
  start = max(0, i - 1)
@@ -93,7 +94,7 @@ def analyze(text):
93
  # Ensure stable math with .float() before softmax
94
  probs = F.softmax(logits.float(), dim=-1)[:, 1].cpu().numpy().tolist()
95
 
96
- # Weighted Scoring: Long sentences have more impact than "Hello."
97
  lengths = [len(s.split()) for s in pure_sents]
98
  total_words = sum(lengths)
99
  weighted_avg = sum(p * l for p, l in zip(probs, lengths)) / total_words if total_words > 0 else 0
@@ -102,36 +103,42 @@ def analyze(text):
102
  # HTML RECONSTRUCTION
103
  # -----------------------------
104
  highlighted_html = "<div style='font-family: sans-serif; line-height: 1.8;'>"
105
- sent_ptr = 0
106
- for block in blocks:
 
 
 
107
  if block.startswith("\n"):
108
  highlighted_html += block.replace("\n", "<br>")
109
  continue
110
  if block.isspace():
111
  highlighted_html += block
112
  continue
113
-
114
- score = probs[sent_ptr]
115
- sent_ptr += 1
116
 
117
- # Define colors based on score
118
- if score < 0.35:
119
- color, bg = "#11823b", "rgba(17, 130, 59, 0.15)"
120
- elif score < 0.70:
121
- color, bg = "#b8860b", "rgba(184, 134, 11, 0.15)"
 
 
 
 
 
 
 
 
 
 
122
  else:
123
- color, bg = "#b80d0d", "rgba(184, 13, 13, 0.15)"
124
 
125
- highlighted_html += (
126
- f"<span style='background:{bg}; padding:2px 4px; border-radius:4px; border-bottom: 2px solid {color};' "
127
- f"title='AI Probability: {score:.1%}'>"
128
- f"<b style='color:{color}; font-size: 0.8em;'>[{score:.0%}]</b> {block}</span>"
129
- )
130
  highlighted_html += "</div>"
131
-
 
132
  label = "AI Content Detected" if weighted_avg >= THRESHOLD else "0 or * AI Content Detected"
 
133
  df = pd.DataFrame({"Sentence": pure_sents, "AI Confidence": [f"{p:.1%}" for p in probs]})
134
-
135
  return label, f"{weighted_avg:.1%}", highlighted_html, df
136
 
137
  # -----------------------------
@@ -140,7 +147,7 @@ def analyze(text):
140
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
141
  gr.Markdown("## πŸ•΅οΈ AI Detector Pro")
142
  gr.Markdown("Sentence-level analysis with weighted context windows.")
143
-
144
  with gr.Row():
145
  with gr.Column(scale=3):
146
  text_input = gr.Textbox(label="Paste Text", lines=12)
@@ -148,13 +155,13 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
148
  with gr.Column(scale=1):
149
  verdict_out = gr.Label(label="Verdict")
150
  score_out = gr.Label(label="Weighted AI Score")
151
-
152
  with gr.Tabs():
153
  with gr.TabItem("Visual Heatmap"):
154
  html_out = gr.HTML()
155
  with gr.TabItem("Raw Data Breakdown"):
156
  table_out = gr.Dataframe(headers=["Sentence", "AI Confidence"], wrap=True)
157
-
158
  run_btn.click(analyze, inputs=text_input, outputs=[verdict_out, score_out, html_out, table_out])
159
 
160
  if __name__ == "__main__":
 
69
  def analyze(text):
70
  if not text.strip():
71
  return "β€”", "β€”", "<em>Please enter text...</em>", None
 
72
  try:
73
  tok, mod = get_model()
74
  except Exception as e:
75
  return "ERROR", "0%", f"Failed to load model: {str(e)}", None
76
 
77
  blocks = split_preserving_structure(text)
78
+ # Track indices of actual sentences to align probabilities correctly
79
+ pure_sents_indices = [i for i, b in enumerate(blocks) if b.strip() and not b.startswith("\n")]
80
+ pure_sents = [blocks[i] for i in pure_sents_indices]
81
+
82
  if not pure_sents:
83
  return "β€”", "β€”", "<em>No sentences detected.</em>", None
84
 
85
+ # Sliding Window (Size 3, Stride 1)
86
  windows = []
87
  for i in range(len(pure_sents)):
88
  start = max(0, i - 1)
 
94
  # Ensure stable math with .float() before softmax
95
  probs = F.softmax(logits.float(), dim=-1)[:, 1].cpu().numpy().tolist()
96
 
97
+ # Weighted Scoring
98
  lengths = [len(s.split()) for s in pure_sents]
99
  total_words = sum(lengths)
100
  weighted_avg = sum(p * l for p, l in zip(probs, lengths)) / total_words if total_words > 0 else 0
 
103
  # HTML RECONSTRUCTION
104
  # -----------------------------
105
  highlighted_html = "<div style='font-family: sans-serif; line-height: 1.8;'>"
106
+
107
+ # Map probabilities to the original block indices
108
+ prob_map = {idx: probs[i] for i, idx in enumerate(pure_sents_indices)}
109
+
110
+ for i, block in enumerate(blocks):
111
  if block.startswith("\n"):
112
  highlighted_html += block.replace("\n", "<br>")
113
  continue
114
  if block.isspace():
115
  highlighted_html += block
116
  continue
 
 
 
117
 
118
+ # Only highlight if the block was actually a sentence we analyzed
119
+ if i in prob_map:
120
+ score = prob_map[i]
121
+ if score < 0.35:
122
+ color, bg = "#11823b", "rgba(17, 130, 59, 0.15)"
123
+ elif score < 0.70:
124
+ color, bg = "#b8860b", "rgba(184, 134, 11, 0.15)"
125
+ else:
126
+ color, bg = "#b80d0d", "rgba(184, 13, 13, 0.15)"
127
+
128
+ highlighted_html += (
129
+ f"<span style='background:{bg}; padding:2px 4px; border-radius:4px; border-bottom: 2px solid {color};' "
130
+ f"title='AI Probability: {score:.1%}'>"
131
+ f"<b style='color:{color}; font-size: 0.8em;'>[{score:.0%}]</b> {block}</span>"
132
+ )
133
  else:
134
+ highlighted_html += block
135
 
 
 
 
 
 
136
  highlighted_html += "</div>"
137
+
138
+ # Restored original labels exactly as requested
139
  label = "AI Content Detected" if weighted_avg >= THRESHOLD else "0 or * AI Content Detected"
140
+
141
  df = pd.DataFrame({"Sentence": pure_sents, "AI Confidence": [f"{p:.1%}" for p in probs]})
 
142
  return label, f"{weighted_avg:.1%}", highlighted_html, df
143
 
144
  # -----------------------------
 
147
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
148
  gr.Markdown("## πŸ•΅οΈ AI Detector Pro")
149
  gr.Markdown("Sentence-level analysis with weighted context windows.")
150
+
151
  with gr.Row():
152
  with gr.Column(scale=3):
153
  text_input = gr.Textbox(label="Paste Text", lines=12)
 
155
  with gr.Column(scale=1):
156
  verdict_out = gr.Label(label="Verdict")
157
  score_out = gr.Label(label="Weighted AI Score")
158
+
159
  with gr.Tabs():
160
  with gr.TabItem("Visual Heatmap"):
161
  html_out = gr.HTML()
162
  with gr.TabItem("Raw Data Breakdown"):
163
  table_out = gr.Dataframe(headers=["Sentence", "AI Confidence"], wrap=True)
164
+
165
  run_btn.click(analyze, inputs=text_input, outputs=[verdict_out, score_out, html_out, table_out])
166
 
167
  if __name__ == "__main__":