CoolFace
Apppublic

Jo10384/Optical_Character_Recognition_System

sourceHugging Facemitupdated 1y agoView on Hugging Face
0likes
app.py55 linesDownload Raw Back to root
1import gradio as gr
2import cv2
3import pytesseract
4from deep_translator import GoogleTranslator
5from langdetect import detect
6import numpy as np
7
8# Pre-processing functions
9
10def preprocess_image(image):
11    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
12    processed_image = cv2.GaussianBlur(gray_image, (3, 3), 0)
13    thresh_image = cv2.adaptiveThreshold(
14        processed_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
15        cv2.THRESH_BINARY, 11, 2
16    )
17    return thresh_image
18
19# OCR function
20
21def perform_ocr(image):
22    custom_config = r'--oem 3 --psm 6'
23    text = pytesseract.image_to_string(image, lang='eng+fra+spa+deu', config=custom_config)
24    return text
25
26# Translation function
27
28def translate_text(text):
29    language = detect(text)
30    translator = GoogleTranslator(source=language, target='en')
31    translated_text = translator.translate(text) if language != 'en' else text
32    return translated_text, language
33
34# Gradio Interface
35
36def ocr_translate_interface(image):
37    preprocessed_image = preprocess_image(image)
38    ocr_text = perform_ocr(preprocessed_image)
39    translated_text, detected_language = translate_text(ocr_text)
40    return {'Detected Language': detected_language, 'Extracted Text': ocr_text, 'Translated Text': translated_text}
41
42iface = gr.Interface(
43    fn=ocr_translate_interface,
44    inputs=gr.Image(type="numpy", label="Upload Image"),
45    outputs=[
46        gr.Label(label="Detected Language"),
47        gr.Textbox(label="Extracted Text"),
48        gr.Textbox(label="Translated Text")
49    ],
50    title="Optical Character Recognition System",
51    description="Upload an image to extract text and translate it to English."
52)
53
54iface.launch()
55