File size: 1,686 Bytes
8c0b69f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from transformers import pipeline
import numpy as np

# Load FREE models
ocr_pipe = pipeline("image-to-text", model="microsoft/trocr-base-handwritten")
similarity_pipe = pipeline("feature-extraction", model="sentence-transformers/all-MiniLM-L6-v2")

def validate_answer(image, user_text, correct_answer):
    # OCR for handwritten text
    if image:
        ocr_result = ocr_pipe(image)
        user_text = ocr_result[0]['generated_text']
    
    # Check clarity (rule-based)
    clarity = sum(c.isalnum() for c in user_text) / max(1, len(user_text))
    if clarity < 0.7:
        return "⚠️ Handwriting unclear", "", ""
    
    # Semantic comparison
    embeddings = similarity_pipe([correct_answer, user_text])
    similarity = np.dot(embeddings[0], embeddings[1])
    
    return (
        f"✅ Clarity: {clarity:.0%}",
        f"📝 Extracted: {user_text}",
        f"🔍 Similarity: {similarity:.0%}"
    )

# Create interface
with gr.Blocks() as demo:
    gr.Markdown("# Free Answer Validator")
    with gr.Row():
        image_input = gr.Image(label="Upload Handwritten Answer", type="pil")
        text_input = gr.Textbox(label="Or Type Answer Here")
    correct_input = gr.Textbox(label="Correct Answer", value="The Earth revolves around the Sun.")
    submit_btn = gr.Button("Validate")
    
    clarity_out = gr.Textbox(label="Clarity Check")
    extracted_out = gr.Textbox(label="Extracted Text")
    similarity_out = gr.Textbox(label="Similarity Score")
    
    submit_btn.click(
        validate_answer,
        inputs=[image_input, text_input, correct_input],
        outputs=[clarity_out, extracted_out, similarity_out]
    )

demo.launch()