Spaces:
Runtime error
Runtime error
File size: 14,338 Bytes
cab828c 4889640 0878198 a48ce8c 0878198 e8225e5 c44ba13 cab828c 0878198 d17776d 0878198 4889640 c44ba13 0878198 4889640 0878198 4889640 0878198 a05af10 0878198 4889640 0878198 ffb2275 0878198 a3b9f5a 0878198 ebdf05f 0878198 5a7e139 60bb5b0 5a7e139 60bb5b0 0878198 147203c 0878198 147203c 0878198 c91126d 0878198 4889640 0878198 4889640 0878198 4889640 0878198 a05af10 4889640 0878198 4889640 0878198 f3c0f47 bdfea90 0878198 f3c0f47 0878198 4889640 0878198 bdfea90 0878198 bdfea90 0878198 bdfea90 0878198 bdfea90 |
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 |
import gradio as gr
from gradio_rich_textbox import RichTextbox
from PIL import Image
from surya.ocr import run_ocr
from surya.model.detection.segformer import load_model as load_det_model, load_processor as load_det_processor
from surya.model.recognition.model import load_model as load_rec_model
from surya.model.recognition.processor import load_processor as load_rec_processor
from lang_list import LANGUAGE_NAME_TO_CODE, TEXT_SOURCE_LANGUAGE_NAMES, S2ST_TARGET_LANGUAGE_NAMES
from gradio_client import Client
from dotenv import load_dotenv
import requests
from io import BytesIO
import cohere
import os
import re
title = "# Welcome to AyaTonic"
description = "Learn a New Language With Aya"
# Load environment variables
load_dotenv()
COHERE_API_KEY = os.getenv('CO_API_KEY')
SEAMLESSM4T = os.getenv('SEAMLESSM4T')
inputlanguage = ""
producetext = "\n\nProduce a complete expositional blog post in {target_language} based on the above :"
formatinputstring = "\n\nthe above text is a learning aid. you must use rich text format to rewrite the above and add 1 . a red color tags for nouns 2. a blue color tag for verbs 3. a green color tag for adjectives and adverbs:"
# Regular expression patterns for each color
patterns = {
"red": r'<span style="color: red;">(.*?)</span>',
"blue": r'<span style="color: blue;">(.*?)</span>',
"green": r'<span style="color: green;">(.*?)</span>',
}
# Dictionaries to hold the matches
matches = {
"red": [],
"blue": [],
"green": [],
}
class TaggedPhraseExtractor:
def __init__(self, text=''):
self.text = text
self.patterns = {}
def set_text(self, text):
"""Set the text to search within."""
self.text = text
def add_pattern(self, color, pattern):
"""Add a new color and its associated pattern."""
self.patterns[color] = pattern
def extract_phrases(self):
"""Extract phrases for all colors and patterns added."""
matches = {color: re.findall(pattern, self.text) for color, pattern in self.patterns.items()}
return matches
def print_phrases(self):
"""Extract phrases and print them."""
matches = self.extract_phrases()
for color, phrases in matches.items():
print(f"Phrases with color {color}:")
for phrase in phrases:
print(f"- {phrase}")
print()
co = cohere.Client(COHERE_API_KEY)
audio_client = Client(SEAMLESSM4T)
def process_audio_to_text(audio_path, inputlanguage="English"):
"""
Convert audio input to text using the Gradio client.
"""
result = audio_client.predict(
audio_path,
inputlanguage,
inputlanguage,
api_name="/s2tt"
)
print("Audio Result: ", result)
return result['text'] # Adjust based on the actual response
def process_text_to_audio(text, target_language="English"):
"""
Convert text input to audio using the Gradio client.
"""
result = audio_client.predict(
text,
target_language,
target_language, # could be make a variation for learning content
api_name="/t2st"
)
return result['audio'] # Adjust based on the actual response
class OCRProcessor:
def __init__(self, langs=["en"]):
self.langs = langs
self.det_processor, self.det_model = load_det_processor(), load_det_model()
self.rec_model, self.rec_processor = load_rec_model(), load_rec_processor()
def process_image(self, image):
"""
Process a PIL image and return the OCR text.
"""
predictions = run_ocr([image], [self.langs], self.det_model, self.det_processor, self.rec_model, self.rec_processor)
return predictions[0] # Assuming the first item in predictions contains the desired text
def process_pdf(self, pdf_path):
"""
Process a PDF file and return the OCR text.
"""
predictions = run_ocr([pdf_path], [self.langs], self.det_model, self.det_processor, self.rec_model, self.rec_processor)
return predictions[0] # Assuming the first item in predictions contains the desired text
def process_input(image=None, file=None, audio=None, text=""):
ocr_processor = OCRProcessor()
final_text = text
if image is not None:
ocr_prediction = ocr_processor.process_image(image)
# gettig text from ocr object
for idx in range(len((list(ocr_prediction)[0][1]))):
final_text += " "
final_text += list((list(ocr_prediction)[0][1])[idx])[1][1]
if file is not None:
if file.name.lower().endswith(('.png', '.jpg', '.jpeg')):
pil_image = Image.open(file)
ocr_prediction = ocr_processor.process_image(pil_image)
# gettig text from ocr object
for idx in range(len((list(ocr_prediction)[0][1]))):
final_text += " "
final_text += list((list(ocr_prediction)[0][1])[idx])[1][1]
elif file.name.lower().endswith('.pdf'):
ocr_prediction = ocr_processor.process_pdf(file.name)
# gettig text from ocr object
for idx in range(len((list(ocr_prediction)[0][1]))):
final_text += " "
final_text += list((list(ocr_prediction)[0][1])[idx])[1][1]
else:
final_text += "\nUnsupported file type."
print("OCR Text: ", final_text)
if audio is not None:
audio_text = process_audio_to_text(audio)
final_text += "\n" + audio_text
final_text_with_producetext = final_text + producetext
response = co.generate(
model='c4ai-aya',
prompt=final_text_with_producetext,
max_tokens=1024,
temperature=0.5
)
# add graceful handling for errors (overflow)
generated_text = response.generations[0].text
print("Generated Text: ", generated_text)
generated_text_with_format = generated_text + "\n" + formatinputstring
response = co.generate(
model='command-nightly',
prompt=generated_text_with_format,
max_tokens=4000,
temperature=0.5
)
processed_text = response.generations[0].text
audio_output = process_text_to_audio(processed_text)
return processed_text, audio_output
# Define Gradio interface
iface = gr.Interface(
fn=process_input,
inputs=[
gr.Image(type="pil", label="Camera Input"),
gr.File(label="File Upload"),
gr.Audio(sources="microphone", type="filepath", label="Mic Input"),
gr.Textbox(lines=2, label="Text Input"),
gr.Dropdown(choices=TEXT_SOURCE_LANGUAGE_NAMES, label="Input Language"),
gr.Dropdown(choices=TEXT_SOURCE_LANGUAGE_NAMES, label="Target Language")
],
outputs=[
RichTextbox(label="Processed Text"),
gr.Audio(label="Audio Output")
],
title=title,
description=description
)
if __name__ == "__main__":
iface.launch()
# co = cohere.Client('yhA228YGeZSl1ctten8LQxw2dky2nngHetXFjV2Q') # This is your trial API key
# response = co.generate(
# model='c4ai-aya',
# prompt='एक यांत्रिक घड़ी दिन के समय को प्रदान करने के लिए एक गैर-इलेक्ट्रॉनिक तंत्र का उपयोग करती है। एक मुख्य स्प्रिंग का उपयोग यांत्रिक तंत्र को ऊर्जा संग्रहीत करने के लिए किया जाता है। एक यांत्रिक घड़ी में दांतों का एक कुंडल होता है जो धीरे-धीरे मुख्य स्प्रिंग से संचालित होता है। दांतों के कुंडल को एक यांत्रिक तंत्र में स्थानांतरित करने के लिए पहियों की एक श्रृंखला का उपयोग किया जाता है जो हाथों को घड़ी के चेहरे पर दाईं ओर ले जाता है। घड़ी के तंत्र को स्थिर करने और यह सुनिश्चित करने के लिए कि हाथ सही दिशा में घूमते हैं, एक कंपन का उपयोग किया जाता है। ',
# max_tokens=3674,
# temperature=0.9,
# k=0,
# stop_sequences=[],
# return_likelihoods='NONE')
# print('Prediction: {}'.format(response.generations[0].text))
# client = Client("https://facebook-seamless-m4t-v2-large.hf.space/--replicas/nq5nn/")
# result = client.predict(
# https://github.com/gradio-app/gradio/raw/main/test/test_files/audio_sample.wav, # filepath in 'Input speech' Audio component
# Afrikaans, # Literal[Afrikaans, Amharic, Armenian, Assamese, Basque, Belarusian, Bengali, Bosnian, Bulgarian, Burmese, Cantonese, Catalan, Cebuano, Central Kurdish, Croatian, Czech, Danish, Dutch, Egyptian Arabic, English, Estonian, Finnish, French, Galician, Ganda, Georgian, German, Greek, Gujarati, Halh Mongolian, Hebrew, Hindi, Hungarian, Icelandic, Igbo, Indonesian, Irish, Italian, Japanese, Javanese, Kannada, Kazakh, Khmer, Korean, Kyrgyz, Lao, Lithuanian, Luo, Macedonian, Maithili, Malayalam, Maltese, Mandarin Chinese, Marathi, Meitei, Modern Standard Arabic, Moroccan Arabic, Nepali, North Azerbaijani, Northern Uzbek, Norwegian Bokmål, Norwegian Nynorsk, Nyanja, Odia, Polish, Portuguese, Punjabi, Romanian, Russian, Serbian, Shona, Sindhi, Slovak, Slovenian, Somali, Southern Pashto, Spanish, Standard Latvian, Standard Malay, Swahili, Swedish, Tagalog, Tajik, Tamil, Telugu, Thai, Turkish, Ukrainian, Urdu, Vietnamese, Welsh, West Central Oromo, Western Persian, Yoruba, Zulu] in 'Source language' Dropdown component
# Bengali, # Literal[Bengali, Catalan, Czech, Danish, Dutch, English, Estonian, Finnish, French, German, Hindi, Indonesian, Italian, Japanese, Korean, Maltese, Mandarin Chinese, Modern Standard Arabic, Northern Uzbek, Polish, Portuguese, Romanian, Russian, Slovak, Spanish, Swahili, Swedish, Tagalog, Telugu, Thai, Turkish, Ukrainian, Urdu, Vietnamese, Welsh, Western Persian] in 'Target language' Dropdown component
# api_name="/s2st"
# )
# print(result)
# co = cohere.Client('yhA228YGeZSl1ctten8LQxw2dky2nngHetXFjV2Q')
# response = co.generate(
# model='command-nightly',
# prompt='Les mécanismes de montres mécaniques\n\nLes mécanismes de montres mécaniques sont des mécanismes qui indiquent la journée, mais pas l\'électronique. Elles utilisent un ressort principal pour stocker l\'énergie nécessaire au fonctionnement des mécanismes. Un train d\'engrenages est utilisé pour transférer l\'énergie du ressort principal à un ensemble de roues qui font tourner les aiguilles dans le sens horaire sur le cadran de la montre.\n\nLes mécanismes de montres mécaniques sontdakshineswar omkarnathji, qui sont des lieux de culte qui sont construits dans le temple. Les engrenages sont des roues qui sont utilisées pour transférer l\'énergie du ressort principal à un ensemble de roues qui font tourner les aiguilles dans le sens horaire sur le cadran de la montre.\n\nLe ressort principal est un ressort qui est utilisé pour stocker l\'énergie nécessaire au fonctionnement des mécanismes de la montre. Le ressort principal est un ressort qui est utilisé pour stocker l\'énergie nécessaire au fonctionnement des mécanismes de la montre, et il est utilisé pour transférer l\'énergie aux engrenages, qui sont des roues qui sont utilisées pour faire tourner les aiguilles dans le sens horaire sur le cadran de la montre.\n\nLes engrenages sont des roues qui sont utilisées pour faire tourner les aiguilles dans le sens horaire sur le cadran de la montre, et elles sont utilisées pour transférer l\'énergie du ressort principal aux roues qui font tourner les aiguilles dans le sens horaire sur le cadran de la montre.\n\nLes mécanismes de montres mécaniques sont des mécanismes qui indiquent la journée, et elles sont utilisées pour transférer l\'énergie du ressort principal à un ensemble de roues qui font tourner les aiguilles dans le sens horaire sur le cadran de la montre.\n\nLes mécanismes de montres mécaniques sont des mécanismes qui indiquent la journée, et elles sont utilisées pour transférer l\'énergie du ressort principal à un ensemble de roues qui font tourner les aiguilles dans le sens horaire sur le cadran de la montre, et elles sont utilisées pour stabiliser le mécanisme de la montre, et pour s\'assurer que les aiguilles tournent dans le bon sens.\n\nthe above text is a learning aid. you must use rich text format to rewrite the above and add 1 . a red color tags for nouns 2. a blue color tag for verbs 3. a green color tag for adjectives and adverbs:',
# max_tokens=7294,
# temperature=0.6,
# k=0,
# stop_sequences=[],
# return_likelihoods='NONE')
# print('Prediction: {}'.format(response.generations[0].text))
# example = RichTextbox().example_inputs()
# iface = gr.Interface(
# fn=process_input,
# inputs=[
# gr.Image(type="pil", label="Camera Input"),
# gr.File(label="File Upload"),
# gr.Audio(sources="microphone", type="filepath", label="Mic Input"),
# gr.Textbox(lines=2, label="Text Input"),
# gr.Dropdown(choices=TEXT_SOURCE_LANGUAGE_NAMES, label="Input Language"),
# gr.Dropdown(choices=TEXT_SOURCE_LANGUAGE_NAMES, label="Target Language")
# ],
# outputs=[
# gr.RichTextbox(label="Processed Text"),
# gr.Audio(label="Audio Output")
# ],
# title="OCR and Speech Processing App",
# description="This app processes images, PDFs, and audio inputs to generate text and audio outputs."
# )
# if __name__ == "__main__":
# # iface.launch()
# demo = gr.Interface(
# lambda x:x,
# RichTextbox(), # interactive version of your component
# RichTextbox(), # static version of your component
# examples=[[example]], # uncomment this line to view the "example version" of your component
# )
# if __name__ == "__main__":
# demo.launch()
|