Update app.py
Browse files
app.py
CHANGED
@@ -1,280 +1,52 @@
|
|
1 |
import os
|
2 |
-
import io
|
3 |
-
import requests
|
4 |
import gradio as gr
|
5 |
-
from
|
6 |
-
from
|
7 |
-
from deep_translator import GoogleTranslator
|
8 |
-
from PIL import Image, ImageDraw
|
9 |
-
import joblib
|
10 |
-
import time
|
11 |
-
from indic_transliteration import sanscript
|
12 |
-
from indic_transliteration.sanscript import transliterate
|
13 |
-
import openai
|
14 |
import torch
|
15 |
-
import warnings
|
16 |
-
from huggingface_hub import InferenceApi
|
17 |
|
18 |
-
# Detect if GPU is available
|
19 |
-
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
20 |
|
21 |
-
|
22 |
-
api_key = os.getenv("GROQ_API_KEY")
|
23 |
-
client = Groq(api_key=api_key)
|
24 |
|
25 |
-
#
|
26 |
-
|
27 |
-
api_key = os.getenv('HF_API_KEY')
|
28 |
-
if api_key is None:
|
29 |
-
raise ValueError("Hugging Face API key is not set. Please set it in your environment.")
|
30 |
|
31 |
-
#
|
32 |
-
|
33 |
|
34 |
-
|
|
|
35 |
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
40 |
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
#
|
46 |
-
|
47 |
-
|
48 |
-
#
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
# Function to query Hugging Face API
|
54 |
-
def query(payload, max_retries=5):
|
55 |
-
for attempt in range(max_retries):
|
56 |
-
response = requests.post(API_URL, headers=headers, json=payload)
|
57 |
-
|
58 |
-
if response.status_code == 503:
|
59 |
-
print(f"Model is still loading, retrying... Attempt {attempt + 1}/{max_retries}")
|
60 |
-
estimated_time = min(response.json().get("estimated_time", 60), 60)
|
61 |
-
time.sleep(estimated_time)
|
62 |
-
continue
|
63 |
-
|
64 |
-
if response.status_code != 200:
|
65 |
-
print(f"Error: Received status code {response.status_code}")
|
66 |
-
print(f"Response: {response.text}")
|
67 |
-
return None
|
68 |
-
|
69 |
-
return response.content
|
70 |
-
|
71 |
-
print(f"Failed to generate image after {max_retries} attempts.")
|
72 |
-
return None
|
73 |
-
|
74 |
-
# Function to generate image
|
75 |
-
def generate_image(prompt):
|
76 |
-
image_bytes = query({"inputs": prompt})
|
77 |
-
|
78 |
-
if image_bytes is None:
|
79 |
-
error_img = Image.new('RGB', (300, 300), color=(255, 0, 0))
|
80 |
-
d = ImageDraw.Draw(error_img)
|
81 |
-
d.text((10, 150), "Image Generation Failed", fill=(255, 255, 255))
|
82 |
-
return error_img
|
83 |
-
|
84 |
-
try:
|
85 |
-
image = Image.open(io.BytesIO(image_bytes))
|
86 |
-
return image
|
87 |
-
except Exception as e:
|
88 |
-
print(f"Error: {e}")
|
89 |
-
error_img = Image.new('RGB', (300, 300), color=(255, 0, 0))
|
90 |
-
d = ImageDraw.Draw(error_img)
|
91 |
-
d.text((10, 150), "Invalid Image Data", fill=(255, 255, 255))
|
92 |
-
return error_img
|
93 |
-
|
94 |
-
# Tamil Audio to Tamil text
|
95 |
-
def transcribe_audio(audio_path):
|
96 |
-
if audio_path is None:
|
97 |
-
return "Please upload an audio file."
|
98 |
-
try:
|
99 |
-
with open(audio_path, "rb") as file:
|
100 |
-
transcription = client.audio.transcriptions.create(
|
101 |
-
file=(os.path.basename(audio_path), file.read()),
|
102 |
-
model="whisper-large-v3",
|
103 |
-
response_format="verbose_json",
|
104 |
-
)
|
105 |
-
return transcription.text
|
106 |
-
except Exception as e:
|
107 |
-
return f"An error occurred: {str(e)}"
|
108 |
-
|
109 |
-
# Transliterate Romanized Tamil (in English letters) to Tamil script
|
110 |
-
def transliterate_to_tamil(romanized_text):
|
111 |
-
try:
|
112 |
-
# Step 1: Normalize the input for better transliteration results
|
113 |
-
romanized_text = romanized_text.strip().lower() # Remove extra spaces and convert to lowercase
|
114 |
-
|
115 |
-
# Step 2: Handle common punctuation that might interrupt transliteration
|
116 |
-
romanized_text = romanized_text.replace(".", " ").replace(",", " ").replace("?", " ").replace("!", " ")
|
117 |
-
|
118 |
-
# Step 3: Apply ITRANS transliteration
|
119 |
-
tamil_text = transliterate(romanized_text, sanscript.ITRANS, sanscript.TAMIL)
|
120 |
-
|
121 |
-
return tamil_text
|
122 |
-
except Exception as e:
|
123 |
-
return f"An error occurred during transliteration: {str(e)}"
|
124 |
-
|
125 |
-
# Function to translate Tamil text to English using deep-translator
|
126 |
-
def translate_tamil_to_english(tamil_text):
|
127 |
-
if not tamil_text:
|
128 |
-
return "Please provide text to translate."
|
129 |
-
try:
|
130 |
-
translator = GoogleTranslator(source='ta', target='en')
|
131 |
-
translated_text = translator.translate(tamil_text)
|
132 |
-
|
133 |
-
# Predict sentiment from translated text
|
134 |
-
sentiment_result = predict_sentiment(translated_text)
|
135 |
-
|
136 |
-
return translated_text, sentiment_result, translated_text
|
137 |
-
except Exception as e:
|
138 |
-
return f"An error occurred during translation: {str(e)}", None, None
|
139 |
-
|
140 |
-
# Function to predict sentiment from English text
|
141 |
-
def predict_sentiment(english_text):
|
142 |
-
if not english_text:
|
143 |
-
return "No text provided for sentiment analysis."
|
144 |
-
try:
|
145 |
-
sentiment = model.predict([english_text])[0]
|
146 |
-
return f"Sentiment: {sentiment}"
|
147 |
-
except Exception as e:
|
148 |
-
return f"An error occurred during sentiment prediction: {str(e)}"
|
149 |
-
|
150 |
-
# Generate creative text based on the translated English text
|
151 |
-
def generate_creative_text(english_text):
|
152 |
-
if not english_text:
|
153 |
-
return "Please provide text to generate creative content."
|
154 |
-
|
155 |
-
try:
|
156 |
-
inputs = text_generation_tokenizer(english_text, return_tensors="pt", padding=True, truncation=True).to(device)
|
157 |
-
|
158 |
-
# Set parameters to control the output and avoid repetition
|
159 |
-
generated_tokens = text_generation_model.generate(
|
160 |
-
**inputs,
|
161 |
-
max_length=60,
|
162 |
-
num_return_sequences=1,
|
163 |
-
no_repeat_ngram_size=3,
|
164 |
-
temperature=0.7,
|
165 |
-
top_p=0.9,
|
166 |
-
do_sample=True,
|
167 |
-
early_stopping=True
|
168 |
-
)
|
169 |
-
|
170 |
-
creative_text = text_generation_tokenizer.decode(generated_tokens[0], skip_special_tokens=True).strip()
|
171 |
-
return creative_text
|
172 |
-
|
173 |
-
except Exception as e:
|
174 |
-
return f"An error occurred during text generation: {str(e)}"
|
175 |
|
176 |
# Create Gradio interface
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
""
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
transcription_output = gr.Textbox(label="Transcription (Tamil or Romanized Tamil)", interactive=True ,elem_id="transcription_output")
|
192 |
-
|
193 |
-
# Button for transliterating Romanized Tamil to Tamil script
|
194 |
-
transliterate_button = gr.Button("Convert to Tamil Script", elem_id="transliterate_btn")
|
195 |
-
|
196 |
-
# Input field for Tamil text and translate button
|
197 |
-
with gr.Row():
|
198 |
-
translate_button = gr.Button("Translate to English", elem_id="translate_btn")
|
199 |
-
|
200 |
-
# Output field for English translation
|
201 |
-
translation_output = gr.Textbox(label="Translation (English)", elem_id="translation_output")
|
202 |
-
|
203 |
-
# Output field for sentiment prediction
|
204 |
-
sentiment_output = gr.Textbox(label="Sentiment", elem_id="sentiment_output")
|
205 |
-
|
206 |
-
# Button to generate creative text
|
207 |
-
creative_text_button = gr.Button("Generate Creative Text", elem_id="creative_btn")
|
208 |
-
|
209 |
-
# Output field for creative text
|
210 |
-
creative_text_output = gr.Textbox(label="Creative Text", elem_id="creative_output")
|
211 |
-
|
212 |
-
# Button to generate image
|
213 |
-
generate_button = gr.Button("Generate Image", elem_id="generate_btn")
|
214 |
-
|
215 |
-
# Output field for image file
|
216 |
-
image_output = gr.Image(label="Generated Image")
|
217 |
-
|
218 |
-
# Define variable to hold the translated English text
|
219 |
-
translated_text_var = gr.State()
|
220 |
-
|
221 |
-
# Define button click actions
|
222 |
-
transcribe_button.click(
|
223 |
-
fn=transcribe_audio,
|
224 |
-
inputs=audio_input,
|
225 |
-
outputs=transcription_output,
|
226 |
-
)
|
227 |
-
|
228 |
-
transliterate_button.click(
|
229 |
-
fn=transliterate_to_tamil,
|
230 |
-
inputs=transcription_output,
|
231 |
-
outputs=transcription_output,
|
232 |
-
)
|
233 |
-
|
234 |
-
translate_button.click(
|
235 |
-
fn=translate_tamil_to_english,
|
236 |
-
inputs=transcription_output,
|
237 |
-
outputs=[translation_output, sentiment_output, translated_text_var],
|
238 |
-
)
|
239 |
-
|
240 |
-
creative_text_button.click(
|
241 |
-
fn=generate_creative_text,
|
242 |
-
inputs=translated_text_var,
|
243 |
-
outputs=creative_text_output,
|
244 |
-
)
|
245 |
-
|
246 |
-
generate_button.click(
|
247 |
-
fn=generate_image,
|
248 |
-
inputs=translated_text_var,
|
249 |
-
outputs=image_output,
|
250 |
-
)
|
251 |
-
|
252 |
-
# Apply custom CSS
|
253 |
-
demo.css = """
|
254 |
-
#transcribe_btn, #transliterate_btn, #translate_btn, #creative_btn, #generate_btn {
|
255 |
-
background-color: #05907B; /* Change button color */
|
256 |
-
color: white; /* Change text color */
|
257 |
-
}
|
258 |
-
|
259 |
-
#translation_output,#transcription_output, #sentiment_output, #creative_output {
|
260 |
-
background-color: #f0f8ff; /* Change background color of text areas */
|
261 |
-
}
|
262 |
-
|
263 |
-
h1 {
|
264 |
-
color: #4CAF50; /* Main heading color */
|
265 |
-
}
|
266 |
-
|
267 |
-
p {
|
268 |
-
color: #000080; /* Plain text color */
|
269 |
-
}
|
270 |
-
|
271 |
-
/* Add thick border to entire app */
|
272 |
-
.gradio-container {
|
273 |
-
border: 5px solid #05907B; /* Thick border color */
|
274 |
-
padding: 10px; /* Padding inside the border */
|
275 |
-
border-radius: 10px; /* Optional: add rounded corners */
|
276 |
-
}
|
277 |
-
"""
|
278 |
-
|
279 |
-
# Launch the interface and ensure code stops afterward
|
280 |
-
demo.launch(share=True)
|
|
|
1 |
import os
|
|
|
|
|
2 |
import gradio as gr
|
3 |
+
from transformers import pipeline
|
4 |
+
from diffusers import StableDiffusionPipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
import torch
|
|
|
|
|
6 |
|
|
|
|
|
7 |
|
8 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
|
|
|
9 |
|
10 |
+
# 1. Tamil to English translator (public model, no token required)
|
11 |
+
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-mul-en")
|
|
|
|
|
|
|
12 |
|
13 |
+
# 2. English text generator (GPT-2, public model, no token required)
|
14 |
+
generator = pipeline("text-generation", model="gpt2")
|
15 |
|
16 |
+
# 3. Stable Diffusion image generator (needs token)
|
17 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
18 |
|
19 |
+
image_pipe = StableDiffusionPipeline.from_pretrained(
|
20 |
+
"CompVis/stable-diffusion-v1-4",
|
21 |
+
use_auth_token=HF_TOKEN,
|
22 |
+
torch_dtype=torch.float16 if device == "cuda" else torch.float32
|
23 |
+
)
|
24 |
+
image_pipe = image_pipe.to(device)
|
25 |
|
26 |
+
def generate_image_from_tamil(tamil_text):
|
27 |
+
# Translate Tamil → English
|
28 |
+
translated = translator(tamil_text, max_length=100)[0]['translation_text']
|
29 |
+
|
30 |
+
# Generate English text from translated sentence
|
31 |
+
generated = generator(translated, max_length=50, num_return_sequences=1)[0]['generated_text']
|
32 |
+
|
33 |
+
# Generate image from generated English text
|
34 |
+
image = image_pipe(generated).images[0]
|
35 |
+
|
36 |
+
return translated, generated, image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
# Create Gradio interface
|
39 |
+
iface = gr.Interface(
|
40 |
+
fn=generate_image_from_tamil,
|
41 |
+
inputs=gr.Textbox(lines=2, label="Enter Tamil Text"),
|
42 |
+
outputs=[
|
43 |
+
gr.Textbox(label="Translated English Text"),
|
44 |
+
gr.Textbox(label="Generated English Prompt"),
|
45 |
+
gr.Image(label="Generated Image")
|
46 |
+
],
|
47 |
+
title="Tamil Text to English and Image Generator",
|
48 |
+
description="Translate Tamil to English, generate English text, and create image using Stable Diffusion."
|
49 |
+
)
|
50 |
+
|
51 |
+
# Launch Gradio app with public link
|
52 |
+
iface.launch(share=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|