Spaces:
Running on Zero
Running on Zero
File size: 19,827 Bytes
315a711 4358b86 c38c6dd 315a711 4358b86 315a711 4358b86 315a711 f17e3df 315a711 78b4d38 315a711 78b4d38 315a711 78b4d38 4358b86 315a711 78b4d38 315a711 78b4d38 315a711 4f5e783 315a711 4358b86 315a711 4358b86 315a711 78b4d38 315a711 78b4d38 315a711 78b4d38 315a711 c38c6dd 315a711 78b4d38 315a711 78b4d38 315a711 78b4d38 315a711 | 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 | # ============================================================
# app.py โ Tortured Phrase Detector (ZeroGPU-compatible)
# ============================================================
import spaces # โ
MUST be the very first import
import os
import re
import json
import torch
import gradio as gr
import pandas as pd
from datetime import datetime
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# CONFIG
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
BASE_MODEL_ID = "meta-llama/Llama-3.2-1B-Instruct"
STANDARD_ADAPTER_ID = "skygg/paperlytix_non_reasoning_medical_trained_adapter"
REASONING_ADAPTER_ID = "skygg/paperlytix_reasoning_medical_trained_adapter"
SONIC_DB_PATH = "./search_tortured_correct.csv"
SONIC_RESULTS_DIR = "./sonic_text_results"
DEEPER_RESULTS_DIR = "./go_deeper_text_results"
HYBRIONIX_RESULTS_DIR = "./hybrionix_text_results"
GO_BEYOND_RESULTS_DIR = "./go_beyond_text_results"
MAX_NEW_TOKENS = 512
MAX_NEW_TOKENS_REASONING = 1024
MAX_INPUT_CHARS = 3000
HF_TOKEN = os.environ.get("HF_TOKEN", None)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# SYSTEM PROMPTS
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
STANDARD_SYSTEM_PROMPT = (
"You are a scientific language correction assistant specializing in "
"Clinical Medicine. Your task is to detect 'tortured phrases' in the "
"given sentence โ these are unnatural, paraphrased substitutions of "
"standard medical terminology, often introduced by paraphrasing tools "
"or paper mills to evade plagiarism detection. Identify each tortured "
"phrase, replace it with the correct and widely accepted clinical term, "
"and briefly explain why the original phrasing is non-standard. If no "
"tortured phrases are found, explicitly state that the sentence uses "
"correct clinical terminology."
)
REASONING_SYSTEM_PROMPT = (
"You are a scientific language correction assistant specializing in "
"Clinical Medicine. Your task is to detect 'tortured phrases' in the "
"given sentence โ these are unnatural, paraphrased substitutions of "
"standard medical terminology, often introduced by paraphrasing tools "
"or paper mills to evade plagiarism detection.\n\n"
"Follow this strict chain-of-thought reasoning process before giving "
"your final answer:\n\n"
"Step 1 - Segment the sentence: Break the sentence into individual "
"medical phrases or noun groups.\n"
"Step 2 - Evaluate each phrase: For each phrase, ask โ Is this a "
"recognized, standard clinical/medical term used in peer-reviewed "
"literature or clinical guidelines? If not, flag it as a potential "
"tortured phrase.\n"
"Step 3 - Identify the distortion pattern: For each flagged phrase, "
"explain what standard term it appears to be paraphrasing and why the "
"substitution is linguistically or clinically non-standard.\n"
"Step 4 - Provide the correction: Replace each tortured phrase with "
"the correct, widely accepted clinical terminology.\n"
"Step 5 - Output the corrected sentence: Present the fully corrected "
"sentence.\n\n"
"If no tortured phrases are found after this reasoning, explicitly "
"state that the sentence uses correct clinical terminology."
)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# GLOBAL MODEL STATE
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
_tokenizer = None
_model = None
_sonic_df = None
def load_models():
"""
Load base model + attach both adapters, then move to 'cuda'
directly โ this is the officially documented ZeroGPU pattern.
The `spaces` package (imported first, above) patches torch so
this call is safe even though no physical GPU is attached to
this process yet; the real transfer happens automatically when
a @spaces.GPU function is later invoked.
NOTE: the adapters are explicitly loaded onto CPU (torch_device="cpu")
because PEFT auto-infers "cuda" as the load device (since `spaces`
reports torch.cuda.is_available() == True) and tries to load the
safetensors weights *directly* onto a real CUDA device โ which fails
with "No CUDA GPUs are available" since no physical GPU is attached
at this point in the process. Loading to CPU first and moving the
whole composed model with `.to("cuda")` afterward is the supported
deferred-placement pattern.
"""
global _tokenizer, _model
print("๐ Loading tokenizer ...")
_tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID, token=HF_TOKEN)
if _tokenizer.pad_token is None:
_tokenizer.pad_token = _tokenizer.eos_token
_tokenizer.pad_token_id = _tokenizer.eos_token_id
print("๐ Loading base LLaMA model ...")
base_model = AutoModelForCausalLM.from_pretrained(
BASE_MODEL_ID,
dtype=torch.float16, # โ
dtype instead of torch_dtype
token=HF_TOKEN
)
print(f"๐ Attaching standard adapter: {STANDARD_ADAPTER_ID}")
_model = PeftModel.from_pretrained(
base_model,
STANDARD_ADAPTER_ID,
adapter_name="standard",
token=HF_TOKEN,
torch_device="cpu"
)
print(f"๐ Attaching reasoning adapter: {REASONING_ADAPTER_ID}")
_model.load_adapter(
REASONING_ADAPTER_ID,
adapter_name="reasoning",
token=HF_TOKEN,
torch_device="cpu"
)
# โโ Official ZeroGPU pattern: move to cuda right after load โ
_model.to("cuda")
_model.eval()
print("โ
Model ready with both adapters, moved to CUDA.\n")
def load_sonic_db():
global _sonic_df
if _sonic_df is None:
print("๐ Loading Sonic helper database ...")
_sonic_df = pd.read_csv(SONIC_DB_PATH, encoding="utf-8")
print(f"โ
Sonic database loaded โ {len(_sonic_df)} pairs.\n")
return _sonic_df
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# SHARED UTILITIES
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def split_into_sentences(text):
raw = re.split(r'(?<=[.!?])\s+', text.strip())
sentences = [s.strip() for s in raw if s.strip()]
return sentences
def validate_input(text):
if not text or not text.strip():
return False, "Please enter some text to analyze."
if len(text) > MAX_INPUT_CHARS:
return False, (
f"Input too long ({len(text)} characters). "
f"Please limit to {MAX_INPUT_CHARS} characters per request."
)
return True, None
def build_pattern(phrase_lower):
escaped = re.escape(phrase_lower)
return re.compile(r'\b' + escaped + r"s?\b", re.IGNORECASE)
def get_next_result_index(folder_path):
os.makedirs(folder_path, exist_ok=True)
existing = [
f for f in os.listdir(folder_path)
if f.startswith("test_") and f.endswith("_results.json")
]
if not existing:
return 1
indices = []
for fname in existing:
try:
idx = int(fname.replace("test_", "").replace("_results.json", ""))
indices.append(idx)
except ValueError:
continue
return max(indices) + 1 if indices else 1
def save_results(folder_path, engine_name, input_text,
sentences, results_per_sentence, extra_data=None):
os.makedirs(folder_path, exist_ok=True)
idx = get_next_result_index(folder_path)
filepath = os.path.join(folder_path, f"test_{idx}_results.json")
output = {
"test_index" : idx,
"engine" : engine_name,
"timestamp" : datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"input_text" : input_text,
"total_sentences" : len(sentences),
"results" : []
}
if extra_data:
output.update(extra_data)
for i, (sentence, result) in enumerate(
zip(sentences, results_per_sentence), start=1
):
output["results"].append({
"sentence_index" : i,
"original" : sentence,
"output" : result
})
with open(filepath, "w", encoding="utf-8") as f:
json.dump(output, f, indent=2, ensure_ascii=False)
return filepath
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ENGINE : SONIC (pure CPU โ CSV lookup, no GPU needed)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def sonic_process_sentence(sentence, df):
found = []
for _, row in df.iterrows():
tortured_lower = str(row["tortured_lower"]).strip()
correct = str(row["correct"]).strip()
tortured_orig = str(row["tortured"]).strip()
pattern = build_pattern(tortured_lower)
match = pattern.search(sentence)
if match:
found.append((tortured_orig, match.group(0), correct))
if not found:
return "No tortured phrases detected."
corrected = sentence
for tortured_orig, matched_text, correct in found:
pattern = build_pattern(tortured_orig.lower())
replacement = correct + "s" if matched_text.lower() == \
(tortured_orig.lower() + "s") else correct
if matched_text[0].isupper():
replacement = replacement[0].upper() + replacement[1:]
corrected = pattern.sub(replacement, corrected, count=1)
lines = [f"Corrected: {corrected}", "", "Tortured phrases detected:"]
for idx, (tortured_orig, matched_text, correct) in enumerate(found, 1):
lines.append(f'{idx}. [Tortured Phrase] "{matched_text}" โ "{correct}"')
return "\n".join(lines)
def run_sonic(sentences):
df = load_sonic_db()
return [sonic_process_sentence(s, df) for s in sentences]
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# GPU-DECORATED GENERATION FUNCTION
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@spaces.GPU(duration=90)
def generate_batch(sentences, adapter_name, system_prompt, max_new_tokens):
"""
ZeroGPU attaches a real GPU only for the duration of this call.
Model is already on 'cuda' (set at load time) โ no device
transfer needed here.
"""
_model.set_adapter(adapter_name)
results = []
for sentence in sentences:
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": sentence}
]
input_text = _tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
inputs = _tokenizer(input_text, return_tensors="pt").to("cuda")
with torch.no_grad():
output_ids = _model.generate(
**inputs,
max_new_tokens = max_new_tokens,
do_sample = False,
pad_token_id = _tokenizer.eos_token_id
)
generated_ids = output_ids[0][inputs["input_ids"].shape[-1]:]
response = _tokenizer.decode(generated_ids, skip_special_tokens=True)
results.append(response.strip())
return results
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# MAIN DISPATCH
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def run_detection(text, engine_choice, progress=gr.Progress()):
is_valid, error = validate_input(text)
if not is_valid:
return f"โ ๏ธ {error}"
sentences = split_into_sentences(text)
progress(0.2, desc="Analyzing your text...")
if engine_choice.startswith("โก"):
results = run_sonic(sentences)
save_results(SONIC_RESULTS_DIR, "Sonic", text, sentences, results)
elif engine_choice.startswith("๐ง "):
progress(0.4, desc="Running AI detection (Go Deeper)...")
results = generate_batch(
sentences, "standard", STANDARD_SYSTEM_PROMPT, MAX_NEW_TOKENS
)
save_results(DEEPER_RESULTS_DIR, "Go Deeper", text, sentences, results)
elif engine_choice.startswith("๐ฎ"):
progress(0.4, desc="Running AI reasoning (Go Beyond)...")
results = generate_batch(
sentences, "reasoning", REASONING_SYSTEM_PROMPT,
MAX_NEW_TOKENS_REASONING
)
save_results(GO_BEYOND_RESULTS_DIR, "Go Beyond", text, sentences, results)
elif engine_choice.startswith("๐"):
progress(0.3, desc="Running Go Deeper (AI)...")
deeper_results = generate_batch(
sentences, "standard", STANDARD_SYSTEM_PROMPT, MAX_NEW_TOKENS
)
progress(0.7, desc="Running Sonic cross-check...")
sonic_results = run_sonic(sentences)
results = []
for d, s_r in zip(deeper_results, sonic_results):
agree = "No tortured phrases" in d and "No tortured phrases" in s_r
if agree:
results.append(f"{d}\n\nโ
Confirmed by both Sonic and Go Deeper.")
else:
results.append(f"{d}\n\n---\n[Sonic cross-check]\n{s_r}")
save_results(
HYBRIONIX_RESULTS_DIR, "Hybrionix", text, sentences, results,
extra_data={
"go_deeper_results": deeper_results,
"sonic_results": sonic_results
}
)
else:
return "โ ๏ธ Please select a valid engine."
progress(0.95, desc="Formatting results...")
output_lines = []
for i, (sentence, result) in enumerate(zip(sentences, results), start=1):
output_lines.append(f"### Sentence {i}")
output_lines.append(f"**Original:** {sentence}")
output_lines.append("")
output_lines.append(result)
output_lines.append("\n---\n")
return "\n".join(output_lines)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# GRADIO INTERFACE
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
ENGINE_CHOICES = [
"โก Sonic (fastest)",
"๐ง Go Deeper (AI, direct)",
"๐ Hybrionix (AI + Sonic)",
"๐ฎ Go Beyond (AI, reasoning)",
]
EXAMPLE_INPUTS = [
["The patient was diagnosed with bosom malignant growth and referred "
"for assessment of cerebrum dead tissue.", "๐ฎ Go Beyond (AI, reasoning)"],
["The patient was diagnosed with myocardial infarction and started on "
"dual antiplatelet therapy.", "โก Sonic (fastest)"],
["Cardiovascular breakdown was noted alongside glucose narrow "
"mindedness in the follow-up report.", "๐ Hybrionix (AI + Sonic)"],
]
DESCRIPTION = """
# ๐ฌ Tortured Phrase Detector โ Clinical Medicine
**What is this?**
A free tool that scans clinical/medical research text for **"tortured phrases"** โ
unnatural, paraphrased substitutions of standard medical terminology often
introduced by paraphrasing tools or paper mills to evade plagiarism detection.
**How to use it:**
1. Paste a sentence or paragraph from a clinical research paper below
2. Choose a detection engine (see guide below)
3. Click **Detect & Correct**
**Choosing an engine:**
| Engine | Speed | Best for |
|---|---|---|
| โก Sonic | Instant | Quick checks, no AI needed |
| ๐ง Go Deeper | Fast (GPU) | AI-powered detection with brief explanations |
| ๐ Hybrionix | Fast (GPU) | Cross-checked results from both Sonic + AI |
| ๐ฎ Go Beyond | Fast (GPU) | Full step-by-step reasoning โ best for review/audit |
โก *Powered by ZeroGPU โ a GPU is allocated on-demand for each AI request.*
"""
with gr.Blocks(title="Tortured Phrase Detector") as demo:
gr.Markdown(DESCRIPTION)
with gr.Row():
with gr.Column():
text_input = gr.Textbox(
label="Paste your sentence(s) here",
placeholder="e.g. The patient was diagnosed with bosom "
"malignant growth...",
lines=6
)
engine_choice = gr.Radio(
choices=ENGINE_CHOICES,
value="โก Sonic (fastest)",
label="Choose your detection engine"
)
submit_btn = gr.Button("๐ Detect & Correct", variant="primary")
with gr.Column():
output_box = gr.Markdown(label="Results")
gr.Examples(
examples=EXAMPLE_INPUTS,
inputs=[text_input, engine_choice],
label="Try an example โฌ๏ธ"
)
submit_btn.click(
fn=run_detection,
inputs=[text_input, engine_choice],
outputs=output_box
)
gr.Markdown(
"---\n"
"โ ๏ธ *This is a research-assistance tool, not a substitute for "
"professional editorial or clinical review.*"
)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# STARTUP
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
for folder in [SONIC_RESULTS_DIR, DEEPER_RESULTS_DIR,
HYBRIONIX_RESULTS_DIR, GO_BEYOND_RESULTS_DIR]:
os.makedirs(folder, exist_ok=True)
print("๐ Loading models at startup ...")
load_models()
load_sonic_db()
print("โ
App ready to launch!")
if __name__ == "__main__":
demo.launch() |