24Sureshkumar commited on
Commit
625a47c
·
verified ·
1 Parent(s): 0724936

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +269 -171
app.py CHANGED
@@ -1,182 +1,280 @@
1
- # Import required libraries
2
- import gradio as gr
3
  import requests
4
- from getpass import getpass
 
 
 
 
 
 
 
 
5
  import openai
6
- from PIL import Image
7
- import io
 
8
 
9
- # Input your Hugging Face and Groq tokens securely
10
- Transalate_token = getpass("Enter Hugging Face Translation Token: ")
11
- Image_Token = getpass("Enter Hugging Face Image Generation Token: ")
12
- Content_Token = getpass("Enter Groq Content Generation Token: ")
13
- Image_prompt_token = getpass("Enter Groq Prompt Generation Token: ")
14
-
15
- # API Keys for GPT and Gemini (replace with your actual keys)
16
- openai.api_key = getpass("Enter OpenAI API Key: ")
17
- # gemini_token = getpass("Enter Gemini API Key: ") # Placeholder, you will need API access
18
-
19
- # API Headers
20
- Translate = {"Authorization": f"Bearer {Transalate_token}"}
21
- Image_generation = {"Authorization": f"Bearer {Image_Token}"}
22
- Content_generation = {
23
- "Authorization": f"Bearer {Content_Token}",
24
- "Content-Type": "application/json"
25
- }
26
- Image_Prompt = {
27
- "Authorization": f"Bearer {Image_prompt_token}",
28
- "Content-Type": "application/json"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  }
30
 
31
- # Translation Model API URL (Tamil to English)
32
- translation_url = "https://api-inference.huggingface.co/models/facebook/mbart-large-50-many-to-one-mmt"
 
33
 
34
- # Text-to-Image Model API URLs
35
- image_generation_urls = {
36
- "black-forest-labs/FLUX.1-schnell": "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell",
37
- "CompVis/stable-diffusion-v1-4": "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4",
38
- "black-forest-labs/FLUX.1-dev": "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-dev"
39
  }
40
 
41
- # Default image generation model
42
- default_image_model = "black-forest-labs/FLUX.1-schnell"
 
43
 
44
- # Content generation models
45
- content_models = {
46
- "GPT-4 (OpenAI)": "gpt-4",
47
- "Gemini-1 (DeepMind)": "gemini-1",
48
- "llama-3.1-70b-versatile": "llama-3.1-70b-versatile",
49
- "mixtral-8x7b-32768": "mixtral-8x7b-32768"
50
  }
 
51
 
52
- # Default content generation model
53
- default_content_model = "GPT-4 (OpenAI)"
54
-
55
- # Function to query Hugging Face translation model
56
- def translate_text(text):
57
- payload = {"inputs": text}
58
- response = requests.post(translation_url, headers=Translate, json=payload)
59
- if response.status_code == 200:
60
- result = response.json()
61
- translated_text = result[0]['generated_text']
62
- return translated_text
63
- else:
64
- return f"Translation Error {response.status_code}: {response.text}"
65
-
66
- # Function to generate content using GPT or Gemini
67
- def generate_content(english_text, max_tokens, temperature, model):
68
- if model == "gpt-4":
69
- # Using OpenAI's GPT model
70
- response = openai.Completion.create(
71
- engine=model, # GPT model (like gpt-4)
72
- prompt=f"Write educational content about {english_text} within {max_tokens} tokens.",
73
- max_tokens=max_tokens,
74
- temperature=temperature
75
- )
76
- return response.choices[0].text.strip()
77
-
78
- # elif model == "gemini-1":
79
- # # Placeholder: Add code to call Gemini API here
80
- # # Using the Gemini API (this requires the correct endpoint and token from Google DeepMind)
81
- # # For example, you would create a POST request similar to OpenAI's API.
82
- # url = "https://api.deepmind.com/gemini/v1/generate"
83
- # headers = {
84
- # "Authorization": f"Bearer {gemini_token}",
85
- # "Content-Type": "application/json"
86
- # }
87
- # payload = {
88
- # "model": "gemini-1",
89
- # "input": f"Write educational content about {english_text} within {max_tokens} tokens.",
90
- # "temperature": temperature,
91
- # "max_tokens": max_tokens
92
- # }
93
- # response = requests.post(url, json=payload, headers=headers)
94
- # if response.status_code == 200:
95
- # return response.json()['choices'][0]['text']
96
- # else:
97
- # return f"Gemini Content Generation Error {response.status_code}: {response.text}"
98
-
99
- else:
100
- # Default to the Groq API or other models if selected
101
- url = "https://api.groq.com/openai/v1/chat/completions"
102
- payload = {
103
- "model": model,
104
- "messages": [
105
- {"role": "system", "content": "You are a creative and insightful writer."},
106
- {"role": "user", "content": f"Write educational content about {english_text} within {max_tokens} tokens."}
107
- ],
108
- "max_tokens": max_tokens,
109
- "temperature": temperature
110
- }
111
- response = requests.post(url, json=payload, headers=Content_generation)
112
- if response.status_code == 200:
113
- result = response.json()
114
- return result['choices'][0]['message']['content']
115
- else:
116
- return f"Content Generation Error: {response.status_code}"
117
-
118
- # Function to generate image prompt
119
- def generate_image_prompt(english_text):
120
- payload = {
121
- "model": "mixtral-8x7b-32768",
122
- "messages": [
123
- {"role": "system", "content": "You are a professional Text to image prompt generator."},
124
- {"role": "user", "content": f"Create a text to image generation prompt about {english_text} within 30 tokens."}
125
- ],
126
- "max_tokens": 30
127
- }
128
- response = requests.post("https://api.groq.com/openai/v1/chat/completions", json=payload, headers=Image_Prompt)
129
- if response.status_code == 200:
130
- result = response.json()
131
- return result['choices'][0]['message']['content']
132
- else:
133
- return f"Prompt Generation Error: {response.status_code}"
134
-
135
- # Function to generate an image from the prompt
136
- def generate_image(image_prompt, model_url):
137
- data = {"inputs": image_prompt}
138
- response = requests.post(model_url, headers=Image_generation, json=data)
139
- if response.status_code == 200:
140
- # Convert the image bytes to a PIL Image
141
- image = Image.open(io.BytesIO(response.content))
142
- # Save image to a temporary file-like object for Gradio
143
- image.save("/tmp/generated_image.png") # Save the image to a file
144
- return "/tmp/generated_image.png" # Return the path to the image
145
- else:
146
- return f"Image Generation Error {response.status_code}: {response.text}"
147
-
148
- # Gradio App
149
- def fusionmind_app(tamil_input, temperature, max_tokens, content_model, image_model):
150
- # Step 1: Translation (Tamil to English)
151
- english_text = translate_text(tamil_input)
152
-
153
- # Step 2: Generate Educational Content
154
- content_output = generate_content(english_text, max_tokens, temperature, content_models[content_model])
155
-
156
- # Step 3: Generate Image from the prompt
157
- image_prompt = generate_image_prompt(english_text)
158
- image_data = generate_image(image_prompt, image_generation_urls[image_model])
159
-
160
- return english_text, content_output, image_data
161
-
162
- # Gradio Interface
163
- interface = gr.Interface(
164
- fn=fusionmind_app,
165
- inputs=[
166
- gr.Textbox(label="Enter Tamil Text"),
167
- gr.Slider(minimum=0.1, maximum=1.0, value=0.7, label="Temperature"),
168
- gr.Slider(minimum=100, maximum=400, value=200, label="Max Tokens for Content Generation"),
169
- gr.Dropdown(list(content_models.keys()), label="Select Content Generation Model", value=default_content_model),
170
- gr.Dropdown(list(image_generation_urls.keys()), label="Select Image Generation Model", value=default_image_model)
171
- ],
172
- outputs=[
173
- gr.Textbox(label="Translated English Text"),
174
- gr.Textbox(label="Generated Content"),
175
- gr.Image(label="Generated Image") # Display the generated image
176
- ],
177
- title="TransArt: A Multimodal Application for Vernacular Language Translation and Image Synthesis",
178
- description="Translate Tamil to English, generate educational content, and generate related images!"
179
- )
180
-
181
- # Launch Gradio App
182
- interface.launch(debug=True)
 
1
+ import os
2
+ import io
3
  import requests
4
+ import gradio as gr
5
+ from groq import Groq
6
+ from transformers import MarianMTModel, MarianTokenizer, AutoModelForCausalLM, AutoTokenizer
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
+ # Set up Groq API key
22
+ api_key = os.getenv("GROQ_API_KEY")
23
+ client = Groq(api_key=api_key)
24
+
25
+ # Set your Hugging Face API key
26
+ os.environ['HF_API_KEY']
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
+ # Set OpenAI API key for text generation
32
+ openai.api_key = os.getenv('OPENAI_API_KEY')
33
+
34
+ headers = {"Authorization": f"Bearer {api_key}"}
35
+
36
+ # Load GPT-Neo for creative text generation
37
+ text_generation_model_name = "EleutherAI/gpt-neo-1.3B"
38
+ text_generation_model = AutoModelForCausalLM.from_pretrained(text_generation_model_name).to(device)
39
+ text_generation_tokenizer = AutoTokenizer.from_pretrained(text_generation_model_name)
40
+
41
+ # Add padding token to GPT-Neo tokenizer if not present
42
+ if text_generation_tokenizer.pad_token is None:
43
+ text_generation_tokenizer.add_special_tokens({'pad_token': '[PAD]'})
44
+
45
+ # Define the API URL for image generation
46
+ API_URL = "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4"
47
+
48
+ # Load the trained sentiment analysis model and preprocessing steps
49
+ with warnings.catch_warnings():
50
+ warnings.simplefilter("ignore")
51
+ model = joblib.load('model.pkl')
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
+ with gr.Blocks() as demo:
178
+ gr.Markdown(
179
+ """
180
+ <h1 style='color: #4CAF50;'>🎙️ Tamil Audio Transcription, Translation, Sentiment Prediction, Creative Text Generation, and Image Generation</h1>
181
+ <p style='color: #000080;'>Upload an audio file to get the Tamil transcription, edit the transcription or type Romanized Tamil to convert it to Tamil script, translate it to English, predict the sentiment of the translated text, generate creative English text, and generate an image.</p>
182
+ """
183
+ )
184
+
185
+ # Input for audio file
186
+ with gr.Row():
187
+ audio_input = gr.Audio(type="filepath", label="Upload Audio File")
188
+ transcribe_button = gr.Button("Transcribe Audio", elem_id="transcribe_btn")
189
+
190
+ # Output field for Tamil transcription with ability to edit or type Romanized Tamil
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)