24Sureshkumar commited on
Commit
0724936
·
verified ·
1 Parent(s): 2e90c14

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +176 -134
app.py CHANGED
@@ -1,140 +1,182 @@
1
- # Install the required libraries
2
- # pip install transformers gradio Pillow requests
3
- import os
4
  import requests
5
- from transformers import MarianMTModel, MarianTokenizer, AutoModelForCausalLM, AutoTokenizer
6
- from PIL import Image, ImageDraw
 
7
  import io
8
- import gradio as gr
9
- import torch
10
-
11
- # Detect if GPU is available
12
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
13
-
14
- # Load the MarianMT model and tokenizer for translation (Tamil to English)
15
- model_name = "Helsinki-NLP/opus-mt-mul-en"
16
- translation_model = MarianMTModel.from_pretrained(model_name).to(device)
17
- translation_tokenizer = MarianTokenizer.from_pretrained(model_name)
18
-
19
- # Load GPT-Neo for creative text generation
20
- text_generation_model_name = "EleutherAI/gpt-neo-1.3B"
21
- text_generation_model = AutoModelForCausalLM.from_pretrained(text_generation_model_name).to(device)
22
- text_generation_tokenizer = AutoTokenizer.from_pretrained(text_generation_model_name)
23
-
24
- # Add padding token to GPT-Neo tokenizer if not present
25
- if text_generation_tokenizer.pad_token is None:
26
- text_generation_tokenizer.add_special_tokens({'pad_token': '[PAD]'})
27
-
28
- # Set your Hugging Face API key
29
- os.environ['HF_API_KEY'] = 'Your_HF_TOKEN' # Replace with your actual API key
30
- api_key = os.getenv('HF_API_KEY')
31
- if api_key is None:
32
- raise ValueError("Hugging Face API key is not set. Please set it in your environment.")
33
-
34
- headers = {"Authorization": f"Bearer {api_key}"}
35
-
36
- # Define the API URL for image generation (replace with actual model URL)
37
- API_URL = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell" # Replace with a valid image generation model
38
-
39
- # Query Hugging Face API to generate image with error handling
40
- def query(payload):
41
- response = requests.post(API_URL, headers=headers, json=payload)
42
- if response.status_code != 200:
43
- print(f"Error: Received status code {response.status_code}")
44
- print(f"Response: {response.text}")
45
- return None
46
- return response.content
47
-
48
- # Translate Tamil text to English
49
- def translate_text(tamil_text):
50
- inputs = translation_tokenizer(tamil_text, return_tensors="pt", padding=True, truncation=True).to(device)
51
- translated_tokens = translation_model.generate(**inputs)
52
- translation = translation_tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
53
- return translation
54
-
55
- # Generate an image based on the translated text with error handling
56
- def generate_image(prompt):
57
- image_bytes = query({"inputs": prompt})
58
-
59
- if image_bytes is None:
60
- # Return a blank image with error message
61
- error_img = Image.new('RGB', (300, 300), color=(255, 0, 0))
62
- d = ImageDraw.Draw(error_img)
63
- d.text((10, 150), "Image Generation Failed", fill=(255, 255, 255))
64
- return error_img
65
-
66
- try:
67
- image = Image.open(io.BytesIO(image_bytes))
68
- return image
69
- except Exception as e:
70
- print(f"Error: {e}")
71
- # Return an error image in case of failure
72
- error_img = Image.new('RGB', (300, 300), color=(255, 0, 0))
73
- d = ImageDraw.Draw(error_img)
74
- d.text((10, 150), "Invalid Image Data", fill=(255, 255, 255))
75
- return error_img
76
-
77
- # Generate creative text based on the translated English text
78
- def generate_creative_text(translated_text):
79
- inputs = text_generation_tokenizer(translated_text, return_tensors="pt", padding=True, truncation=True).to(device)
80
- generated_tokens = text_generation_model.generate(**inputs, max_length=100)
81
- creative_text = text_generation_tokenizer.decode(generated_tokens[0], skip_special_tokens=True)
82
- return creative_text
83
-
84
- # Function to handle the full workflow
85
- def translate_generate_image_and_text(tamil_text):
86
- # Step 1: Translate Tamil to English
87
- translated_text = translate_text(tamil_text)
88
-
89
- # Step 2: Generate an image from the translated text
90
- image = generate_image(translated_text)
91
-
92
- # Step 3: Generate creative text from the translated text
93
- creative_text = generate_creative_text(translated_text)
94
-
95
- return translated_text, creative_text, image
96
-
97
- # Create a visually appealing Gradio interface
98
- css = """
99
- #transart-title {
100
- font-size: 2.5em;
101
- font-weight: bold;
102
- color: #4CAF50;
103
- text-align: center;
104
- margin-bottom: 10px;
105
  }
106
- #transart-subtitle {
107
- font-size: 1.25em;
108
- text-align: center;
109
- color: #555555;
110
- margin-bottom: 20px;
111
  }
112
- body {
113
- background-color: #f0f0f5;
 
 
 
 
 
 
 
114
  }
115
- .gradio-container {
116
- font-family: 'Arial', sans-serif;
 
 
 
 
 
 
 
 
117
  }
118
- """
119
-
120
- # Custom HTML for title and subtitle (can be displayed in Markdown)
121
- title_markdown = """
122
- # <div id="transart-title">TransArt</div>
123
- ### <div id="transart-subtitle">Tamil to English Translation, Creative Text & Image Generation</div>
124
- """
125
-
126
- # Gradio interface with customized layout and aesthetics
127
- with gr.Blocks(css=css) as interface:
128
- gr.Markdown(title_markdown) # Title and subtitle in Markdown
129
- with gr.Row():
130
- with gr.Column():
131
- tamil_input = gr.Textbox(label="Enter Tamil Text", placeholder="Type Tamil text here...", lines=3) # Input for Tamil text
132
- with gr.Column():
133
- translated_output = gr.Textbox(label="Translated Text", interactive=False) # Output for translated text
134
- creative_text_output = gr.Textbox(label="Creative Generated Text", interactive=False) # Output for creative text
135
- generated_image_output = gr.Image(label="Generated Image") # Output for generated image
136
-
137
- gr.Button("Generate").click(fn=translate_generate_image_and_text, inputs=tamil_input, outputs=[translated_output, creative_text_output, generated_image_output])
138
-
139
- # Launch the Gradio app
140
- interface.launch(debug=True, server_name="0.0.0.0")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)