Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,13 +8,15 @@ from transformers import AutoProcessor, AutoModelForImageTextToText, Qwen2_5_VLF
|
|
| 8 |
from reportlab.platypus import SimpleDocTemplate, Paragraph
|
| 9 |
from reportlab.lib.styles import getSampleStyleSheet
|
| 10 |
from docx import Document
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# ---------------- Models ----------------
|
| 13 |
MODEL_PATHS = {
|
| 14 |
"Model 1 (Complex handwrittings )": ("prithivMLmods/Qwen2.5-VL-7B-Abliterated-Caption-it", Qwen2_5_VLForConditionalGeneration),
|
| 15 |
"Model 2 (simple and scanned handwritting )": ("nanonets/Nanonets-OCR-s", Qwen2_5_VLForConditionalGeneration),
|
| 16 |
-
"Model 3 (structured handwritting)": ("Emeritus-21/Finetuned-full-HTR-model", AutoModelForImageTextToText),
|
| 17 |
}
|
|
|
|
| 18 |
|
| 19 |
MAX_NEW_TOKENS_DEFAULT = 512
|
| 20 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
@@ -62,12 +64,10 @@ def _build_inputs(processor, tokenizer, image: Image.Image, prompt: str):
|
|
| 62 |
def _decode_text(model, processor, tokenizer, output_ids, prompt: str):
|
| 63 |
try:
|
| 64 |
decoded_text = processor.batch_decode(output_ids, skip_special_tokens=True)[0]
|
| 65 |
-
# Remove the prompt text and any preceding content to ensure only the transcription remains
|
| 66 |
prompt_start = decoded_text.find(prompt)
|
| 67 |
if prompt_start != -1:
|
| 68 |
decoded_text = decoded_text[prompt_start + len(prompt):].strip()
|
| 69 |
else:
|
| 70 |
-
# If prompt is not found, return the stripped decoded text
|
| 71 |
decoded_text = decoded_text.strip()
|
| 72 |
return decoded_text
|
| 73 |
except Exception:
|
|
@@ -133,7 +133,6 @@ def save_as_audio(text):
|
|
| 133 |
text = _safe_text(text)
|
| 134 |
if not text: return None
|
| 135 |
try:
|
| 136 |
-
from gTTS import gTTS
|
| 137 |
tts = gTTS(text)
|
| 138 |
tts.save("output.mp3")
|
| 139 |
return "output.mp3"
|
|
@@ -141,10 +140,39 @@ def save_as_audio(text):
|
|
| 141 |
print(f"gTTS failed: {e}")
|
| 142 |
return None
|
| 143 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
# ---------------- Gradio Interface ----------------
|
| 145 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 146 |
gr.Markdown("## βπΎ wilson Handwritten OCR")
|
| 147 |
model_choice = gr.Radio(choices=list(MODEL_PATHS.keys()), value=list(MODEL_PATHS.keys())[0], label="Select OCR Model")
|
|
|
|
| 148 |
with gr.Tab("πΌ Image Inference"):
|
| 149 |
query_input = gr.Textbox(label="Custom Prompt (optional)", placeholder="Leave empty for RAW structured output")
|
| 150 |
image_input = gr.Image(type="pil", label="Upload / Capture Handwritten Image", sources=["upload", "webcam"])
|
|
@@ -168,5 +196,26 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 168 |
audio_btn.click(fn=save_as_audio, inputs=[raw_output], outputs=[audio_file])
|
| 169 |
clear_btn.click(fn=lambda: ("", None, "", MAX_NEW_TOKENS_DEFAULT, 0.1, 1.0, 0, 1.0), outputs=[raw_output, image_input, query_input, max_new_tokens, temperature, top_p, top_k, repetition_penalty])
|
| 170 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
if __name__ == "__main__":
|
| 172 |
demo.queue(max_size=50).launch(share=True)
|
|
|
|
| 8 |
from reportlab.platypus import SimpleDocTemplate, Paragraph
|
| 9 |
from reportlab.lib.styles import getSampleStyleSheet
|
| 10 |
from docx import Document
|
| 11 |
+
from gTTS import gTTS
|
| 12 |
+
from jiwer import cer
|
| 13 |
|
| 14 |
# ---------------- Models ----------------
|
| 15 |
MODEL_PATHS = {
|
| 16 |
"Model 1 (Complex handwrittings )": ("prithivMLmods/Qwen2.5-VL-7B-Abliterated-Caption-it", Qwen2_5_VLForConditionalGeneration),
|
| 17 |
"Model 2 (simple and scanned handwritting )": ("nanonets/Nanonets-OCR-s", Qwen2_5_VLForConditionalGeneration),
|
|
|
|
| 18 |
}
|
| 19 |
+
# Model 3 has been removed to conserve memory.
|
| 20 |
|
| 21 |
MAX_NEW_TOKENS_DEFAULT = 512
|
| 22 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
| 64 |
def _decode_text(model, processor, tokenizer, output_ids, prompt: str):
|
| 65 |
try:
|
| 66 |
decoded_text = processor.batch_decode(output_ids, skip_special_tokens=True)[0]
|
|
|
|
| 67 |
prompt_start = decoded_text.find(prompt)
|
| 68 |
if prompt_start != -1:
|
| 69 |
decoded_text = decoded_text[prompt_start + len(prompt):].strip()
|
| 70 |
else:
|
|
|
|
| 71 |
decoded_text = decoded_text.strip()
|
| 72 |
return decoded_text
|
| 73 |
except Exception:
|
|
|
|
| 133 |
text = _safe_text(text)
|
| 134 |
if not text: return None
|
| 135 |
try:
|
|
|
|
| 136 |
tts = gTTS(text)
|
| 137 |
tts.save("output.mp3")
|
| 138 |
return "output.mp3"
|
|
|
|
| 140 |
print(f"gTTS failed: {e}")
|
| 141 |
return None
|
| 142 |
|
| 143 |
+
# ---------------- Metrics Function ----------------
|
| 144 |
+
def calculate_cer_score(ground_truth: str, prediction: str) -> str:
|
| 145 |
+
"""
|
| 146 |
+
Calculates the Character Error Rate (CER) between two strings.
|
| 147 |
+
A CER of 0.0 means the prediction is perfect.
|
| 148 |
+
"""
|
| 149 |
+
if not ground_truth or not prediction:
|
| 150 |
+
return "Cannot calculate CER: Missing ground truth or prediction."
|
| 151 |
+
|
| 152 |
+
ground_truth_cleaned = " ".join(ground_truth.strip().split())
|
| 153 |
+
prediction_cleaned = " ".join(prediction.strip().split())
|
| 154 |
+
|
| 155 |
+
error_rate = cer(ground_truth_cleaned, prediction_cleaned)
|
| 156 |
+
return f"Character Error Rate (CER): {error_rate:.4f}"
|
| 157 |
+
|
| 158 |
+
# ---------------- Evaluation Orchestration ----------------
|
| 159 |
+
@spaces.GPU
|
| 160 |
+
def perform_evaluation(image: Image.Image, model_name: str, ground_truth: str,
|
| 161 |
+
max_new_tokens: int, temperature: float, top_p: float, top_k: int, repetition_penalty: float):
|
| 162 |
+
if image is None or not ground_truth:
|
| 163 |
+
return "Please upload an image and provide the ground truth.", "N/A"
|
| 164 |
+
|
| 165 |
+
prediction = ocr_image(image, model_name, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p, top_k=top_k, repetition_penalty=repetition_penalty)
|
| 166 |
+
|
| 167 |
+
cer_score = calculate_cer_score(ground_truth, prediction)
|
| 168 |
+
|
| 169 |
+
return prediction, cer_score
|
| 170 |
+
|
| 171 |
# ---------------- Gradio Interface ----------------
|
| 172 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 173 |
gr.Markdown("## βπΎ wilson Handwritten OCR")
|
| 174 |
model_choice = gr.Radio(choices=list(MODEL_PATHS.keys()), value=list(MODEL_PATHS.keys())[0], label="Select OCR Model")
|
| 175 |
+
|
| 176 |
with gr.Tab("πΌ Image Inference"):
|
| 177 |
query_input = gr.Textbox(label="Custom Prompt (optional)", placeholder="Leave empty for RAW structured output")
|
| 178 |
image_input = gr.Image(type="pil", label="Upload / Capture Handwritten Image", sources=["upload", "webcam"])
|
|
|
|
| 196 |
audio_btn.click(fn=save_as_audio, inputs=[raw_output], outputs=[audio_file])
|
| 197 |
clear_btn.click(fn=lambda: ("", None, "", MAX_NEW_TOKENS_DEFAULT, 0.1, 1.0, 0, 1.0), outputs=[raw_output, image_input, query_input, max_new_tokens, temperature, top_p, top_k, repetition_penalty])
|
| 198 |
|
| 199 |
+
with gr.Tab("π Model Evaluation"):
|
| 200 |
+
gr.Markdown("### π Evaluate Model Accuracy")
|
| 201 |
+
eval_image_input = gr.Image(type="pil", label="Upload Image for Evaluation", sources=["upload"])
|
| 202 |
+
eval_ground_truth = gr.Textbox(label="Ground Truth (Correct Transcription)", lines=10, placeholder="Type or paste the correct text here.")
|
| 203 |
+
eval_model_output = gr.Textbox(label="Model's Prediction", lines=10, interactive=False, show_copy_button=True)
|
| 204 |
+
eval_cer_output = gr.Textbox(label="Metrics", interactive=False)
|
| 205 |
+
|
| 206 |
+
with gr.Row():
|
| 207 |
+
run_evaluation_btn = gr.Button("π Run OCR and Evaluate", variant="primary")
|
| 208 |
+
clear_evaluation_btn = gr.Button("π§Ή Clear")
|
| 209 |
+
|
| 210 |
+
run_evaluation_btn.click(
|
| 211 |
+
fn=perform_evaluation,
|
| 212 |
+
inputs=[eval_image_input, model_choice, eval_ground_truth, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
|
| 213 |
+
outputs=[eval_model_output, eval_cer_output]
|
| 214 |
+
)
|
| 215 |
+
clear_evaluation_btn.click(
|
| 216 |
+
fn=lambda: (None, "", "", ""),
|
| 217 |
+
outputs=[eval_image_input, eval_ground_truth, eval_model_output, eval_cer_output]
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
if __name__ == "__main__":
|
| 221 |
demo.queue(max_size=50).launch(share=True)
|