IotaCluster commited on
Commit
c5be93e
·
verified ·
1 Parent(s): 6a25ef0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -0
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pytesseract
3
+ from PIL import Image
4
+ from transformers import MarianMTModel, MarianTokenizer
5
+ from nltk.tokenize import sent_tokenize
6
+ import nltk
7
+
8
+ nltk.download('punkt')
9
+
10
+ # OCR function
11
+ def ocr_image(image, language):
12
+ if image is None:
13
+ return "Please upload an image."
14
+ lang = '+'.join(language)
15
+ text = pytesseract.image_to_string(image, lang=lang)
16
+ return text.strip()
17
+
18
+ # Translation function
19
+ def translate_text(text, direction):
20
+ if not text.strip():
21
+ return "No text to translate."
22
+ src, tgt = direction.split("-")
23
+ model_name = f"Helsinki-NLP/opus-mt-{src}-{tgt}"
24
+
25
+ tokenizer = MarianTokenizer.from_pretrained(model_name)
26
+ model = MarianMTModel.from_pretrained(model_name)
27
+
28
+ sentences = sent_tokenize(text)
29
+ inputs = tokenizer(sentences, return_tensors="pt", padding=True, truncation=True)
30
+ outputs = model.generate(**inputs)
31
+
32
+ translated = [tokenizer.decode(t, skip_special_tokens=True) for t in outputs]
33
+ return "\n".join(translated).strip()
34
+
35
+ # Gradio Interface
36
+ iface = gr.Interface(
37
+ fn=ocr_image,
38
+ inputs=[
39
+ gr.Image(type="pil", label="Image"),
40
+ gr.CheckboxGroup(choices=["eng", "chi_sim", "fra", "deu"], value=["eng"], label="OCR Language(s)")
41
+ ],
42
+ outputs="text",
43
+ title="OCR Text Extractor"
44
+ )
45
+
46
+ # Add translation separately
47
+ translate_iface = gr.Interface(
48
+ fn=translate_text,
49
+ inputs=[
50
+ gr.Textbox(label="Text to Translate"),
51
+ gr.Radio(choices=["en-zh", "zh-en", "en-fr", "fr-en"], value="en-zh", label="Translation Direction")
52
+ ],
53
+ outputs="text",
54
+ title="Text Translator"
55
+ )
56
+
57
+ # Combine both as a tabbed app
58
+ gr.TabbedInterface([iface, translate_iface], ["OCR", "Translate"]).launch()