24Sureshkumar commited on
Commit
4deb4b5
·
verified ·
1 Parent(s): ddb377a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +272 -110
app.py CHANGED
@@ -1,61 +1,82 @@
1
  # app.py
2
-
3
- import gradio as gr
4
  from transformers import pipeline
5
- from diffusers import StableDiffusionPipeline
6
  import torch
7
  import re
8
  import os
9
  from huggingface_hub import login
 
 
 
 
 
 
 
 
 
 
10
 
11
  # Get Hugging Face token from environment variable
12
  HF_TOKEN = os.environ.get("HF_TOKEN")
13
  if not HF_TOKEN:
14
- raise ValueError("Hugging Face token not found in environment variables!")
 
15
  else:
16
  login(token=HF_TOKEN)
17
 
18
- # Load all models
 
 
 
 
19
  def load_models():
20
- # Translation model: Tamil English
21
- translator = pipeline(
22
- "translation",
23
- model="facebook/nllb-200-distilled-600M",
24
- src_lang="tam_Taml",
25
- tgt_lang="eng_Latn",
26
- device=0 if torch.cuda.is_available() else -1,
27
- use_auth_token=HF_TOKEN
28
- )
29
-
30
- # Text generation model
31
- text_generator = pipeline(
32
- "text-generation",
33
- model="gpt2-medium",
34
- device=0 if torch.cuda.is_available() else -1,
35
- use_auth_token=HF_TOKEN
36
- )
37
-
38
- # Stable Diffusion for image generation
39
- if torch.cuda.is_available():
40
- image_pipe = StableDiffusionPipeline.from_pretrained(
41
- "runwayml/stable-diffusion-v1-5",
42
- torch_dtype=torch.float16,
43
- revision="fp16",
44
- use_auth_token=HF_TOKEN
45
- ).to("cuda")
46
- else:
47
- image_pipe = StableDiffusionPipeline.from_pretrained(
48
- "runwayml/stable-diffusion-v1-5",
49
- use_auth_token=HF_TOKEN
50
  )
51
 
52
- return translator, text_generator, image_pipe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
- # Load models once at startup
 
 
55
  try:
56
  translator, text_generator, image_pipe = load_models()
57
  except Exception as e:
58
- raise RuntimeError(f"Model loading failed: {str(e)}")
 
59
 
60
  # Clean generated text
61
  def clean_text(text):
@@ -66,80 +87,221 @@ def clean_text(text):
66
  # Main processing function
67
  def process_content(tamil_input, creativity_level):
68
  try:
 
 
 
69
  # Translation
70
- translation_result = translator(tamil_input)
71
- english_text = translation_result[0]['translation_text']
72
-
 
73
  # Image generation
74
- image = image_pipe(
75
- english_text,
76
- guidance_scale=creativity_level,
77
- num_inference_steps=30
78
- ).images[0]
79
-
 
 
 
80
  # Text generation
81
- creative_output = text_generator(
82
- f"Create creative content about: {english_text}",
83
- max_length=150,
84
- temperature=creativity_level / 10,
85
- num_return_sequences=1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  )
 
 
 
 
 
 
 
 
 
87
 
88
- return english_text, clean_text(creative_output[0]['generated_text']), image, ""
89
- except Exception as e:
90
- return "", "", None, f"⚠️ Error: {str(e)}"
91
-
92
- # Gradio UI
93
- with gr.Blocks(theme=gr.themes.Soft()) as app:
94
- gr.Markdown("# 🌐 தமிழ் உரை முதல் பட உருவாக்கம் (Tamil to Image Generator)")
95
- gr.Markdown("தமிழில் உள்ளீடு செய்து → ஆங்கில மொழிபெயர்ப்பு + AI உருவம் + படைப்பு உரை பெறவும்")
96
-
97
- with gr.Row():
98
- with gr.Column():
99
- tamil_input = gr.Textbox(
100
- label="தமிழ் உள்ளீடு",
101
- placeholder="உதாரணம்: பனி படர்ந்த குளிர்காலத்தில் வெப்பமான காபி குடிக்கும் பழங்குடி பெண்",
102
- lines=3
103
- )
104
- creativity = gr.Slider(
105
- label="படைப்பாற்றல் நிலை",
106
- minimum=1, maximum=10, value=7, step=1
107
- )
108
- submit_btn = gr.Button("உருவாக்கு")
109
-
110
- with gr.Column():
111
- translation_box = gr.Textbox(label="ஆங்கில மொழிபெயர்ப்பு")
112
- creative_output = gr.Textbox(label="படைப்பு உரை", lines=3)
113
- image_output = gr.Image(label="உருவாக்கப்பட்ட படம்")
114
- error_output = gr.Textbox(label="பிழை செய்திகள்", visible=True)
115
-
116
- # Example inputs
117
- examples = gr.Examples(
118
- examples=[
119
- ["கடலின் அடியில் மறைந்திருக்கும் பழைய நகரம்", 8],
120
- ["பனி படர்ந்த குளிர்காலத்தில் வெப்பமான காபி குடிக்கும் பழங்குடி பெண்", 7],
121
- ["வேறு கிரகத்தில் இருந்து வந்த அறிவார்ந்த இயந்திரங்கள்", 9]
122
- ],
123
- inputs=[tamil_input, creativity]
124
- )
125
-
126
- # Clear all inputs/outputs
127
- clear_btn = gr.Button("துடைத்து துவக்கவும்")
128
- def clear_all():
129
- return "", "", "", None, ""
130
-
131
- submit_btn.click(
132
- fn=process_content,
133
- inputs=[tamil_input, creativity],
134
- outputs=[translation_box, creative_output, image_output, error_output]
135
- )
136
-
137
- clear_btn.click(
138
- fn=clear_all,
139
- inputs=[],
140
- outputs=[tamil_input, translation_box, creative_output, image_output, error_output]
141
- )
142
-
143
- # Launch the app
144
- if __name__ == "__main__":
145
- app.queue().launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # app.py
2
+ import streamlit as st
 
3
  from transformers import pipeline
4
+ from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler
5
  import torch
6
  import re
7
  import os
8
  from huggingface_hub import login
9
+ import time
10
+ import io
11
+
12
+ # Set page config
13
+ st.set_page_config(
14
+ page_title="தமிழ் உரை முதல் பட உருவாக்கம்",
15
+ page_icon="🖼️",
16
+ layout="wide",
17
+ initial_sidebar_state="expanded"
18
+ )
19
 
20
  # Get Hugging Face token from environment variable
21
  HF_TOKEN = os.environ.get("HF_TOKEN")
22
  if not HF_TOKEN:
23
+ st.error("Hugging Face token not found in environment variables!")
24
+ st.stop()
25
  else:
26
  login(token=HF_TOKEN)
27
 
28
+ # Global flag for safety checker
29
+ SAFETY_CHECK_ENABLED = True
30
+
31
+ # Cache model loading
32
+ @st.cache_resource(show_spinner=False)
33
  def load_models():
34
+ with st.spinner("மாதிரிகள் ஏற்றப்படுகின்றன... இது சில நிமிடங்கள் எடுக்கலாம்"):
35
+ # Translation model: Tamil → English
36
+ translator = pipeline(
37
+ "translation",
38
+ model="facebook/nllb-200-distilled-600M",
39
+ src_lang="tam_Taml",
40
+ tgt_lang="eng_Latn",
41
+ device=0 if torch.cuda.is_available() else -1,
42
+ token=HF_TOKEN
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  )
44
 
45
+ # Text generation model
46
+ text_generator = pipeline(
47
+ "text-generation",
48
+ model="gpt2-medium",
49
+ device=0 if torch.cuda.is_available() else -1,
50
+ token=HF_TOKEN
51
+ )
52
+
53
+ # Stable Diffusion for image generation
54
+ if torch.cuda.is_available():
55
+ image_pipe = StableDiffusionPipeline.from_pretrained(
56
+ "runwayml/stable-diffusion-v1-5",
57
+ torch_dtype=torch.float16,
58
+ revision="fp16",
59
+ token=HF_TOKEN,
60
+ safety_checker=None if not SAFETY_CHECK_ENABLED else None
61
+ )
62
+ image_pipe.scheduler = DPMSolverMultistepScheduler.from_config(image_pipe.scheduler.config)
63
+ image_pipe = image_pipe.to("cuda")
64
+ image_pipe.enable_attention_slicing()
65
+ else:
66
+ image_pipe = StableDiffusionPipeline.from_pretrained(
67
+ "runwayml/stable-diffusion-v1-5",
68
+ token=HF_TOKEN
69
+ )
70
+ image_pipe.enable_attention_slicing()
71
 
72
+ return translator, text_generator, image_pipe
73
+
74
+ # Load models
75
  try:
76
  translator, text_generator, image_pipe = load_models()
77
  except Exception as e:
78
+ st.error(f"மாதிரிகள் ஏற்றுவதில் தோல்வி: {str(e)}")
79
+ st.stop()
80
 
81
  # Clean generated text
82
  def clean_text(text):
 
87
  # Main processing function
88
  def process_content(tamil_input, creativity_level):
89
  try:
90
+ # Track processing time
91
+ start_time = time.time()
92
+
93
  # Translation
94
+ with st.spinner("மொழிபெயர்ப்பு... (Translating)"):
95
+ translation_result = translator(tamil_input)
96
+ english_text = translation_result[0]['translation_text']
97
+
98
  # Image generation
99
+ with st.spinner("படம் உருவாக்கப்படுகிறது... (Generating Image)"):
100
+ image = image_pipe(
101
+ english_text,
102
+ guidance_scale=7 + creativity_level, # Range 8-17
103
+ num_inference_steps=30 + creativity_level * 2,
104
+ height=512,
105
+ width=512
106
+ ).images[0]
107
+
108
  # Text generation
109
+ with st.spinner("உரை உருவாக்கப்படுகிறது... (Generating Text)"):
110
+ creative_output = text_generator(
111
+ f"Create creative content about: {english_text}",
112
+ max_length=150,
113
+ temperature=creativity_level / 10,
114
+ num_return_sequences=1
115
+ )
116
+ cleaned_text = clean_text(creative_output[0]['generated_text'])
117
+
118
+ # Calculate processing time
119
+ proc_time = time.time() - start_time
120
+
121
+ return english_text, cleaned_text, image, f"⏱️ செயலாக்க நேரம்: {proc_time:.1f} வினாடிகள்", ""
122
+
123
+ except torch.cuda.OutOfMemoryError:
124
+ torch.cuda.empty_cache()
125
+ return "", "", None, "", "⚠️ GPU மெமரி நிரம்பிவிட்டது! தயவுசெய்து உள்ளீட்டை குறைக்கவும் அல்லது படைப்புத்திறன் அளவை குறைக்கவும்"
126
+ except Exception as e:
127
+ return "", "", None, "", f"⚠️ பிழை: {str(e)}"
128
+
129
+ # Initialize session state
130
+ if 'tamil_input' not in st.session_state:
131
+ st.session_state.tamil_input = ""
132
+ if 'creativity' not in st.session_state:
133
+ st.session_state.creativity = 7
134
+ if 'outputs' not in st.session_state:
135
+ st.session_state.outputs = []
136
+
137
+ # Custom CSS for Tamil font support
138
+ def local_css(file_name):
139
+ try:
140
+ with open(file_name) as f:
141
+ st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)
142
+ except:
143
+ st.markdown("""
144
+ <style>
145
+ @import url('https://fonts.googleapis.com/css2?family=Catamaran:wght@400;700&family=Hind+Madurai:wght@400;700&display=swap');
146
+
147
+ /* Apply Tamil font to specific elements */
148
+ body, .stTextArea>label, .stSlider>label, .stButton>button, .stSelectbox>label {
149
+ font-family: 'Catamaran', 'Hind Madurai', sans-serif !important;
150
+ }
151
+
152
+ /* Custom styling */
153
+ .stTextInput input, .stTextArea textarea {
154
+ border: 2px solid #4CAF50 !important;
155
+ }
156
+
157
+ .stButton>button {
158
+ background-color: #4CAF50 !important;
159
+ color: white !important;
160
+ font-weight: bold;
161
+ }
162
+
163
+ .stSlider>div>div>div>div {
164
+ background-color: #4CAF50 !important;
165
+ }
166
+ </style>
167
+ """, unsafe_allow_html=True)
168
+
169
+ # Apply CSS
170
+ local_css("style.css")
171
+
172
+ st.title("🌐 தமிழ் உரை முதல் பட உருவாக்கம்")
173
+ st.markdown("தமிழில் உள்ளீடு செய்து → ஆங்கில மொழிபெயர்ப்பு + AI உருவம் + படைப்பு உரை பெறவும்")
174
+
175
+ # Sidebar with examples and info
176
+ with st.sidebar:
177
+ st.header("உதாரணங்கள்")
178
+ examples = [
179
+ ("கடலின் அடியில் மறைந்திருக்கும் பழைய நகரம்", 8),
180
+ ("பனி படர்ந்த குளிர்காலத்தில் வெப்பமான காபி குடிக்கும் பழங்குடி பெண்", 7),
181
+ ("வேறு கிரகத்தில் இருந்து வந்த அறிவார்ந்த இயந்திரங்கள்", 9)
182
+ ]
183
+
184
+ for text, creativity in examples:
185
+ if st.button(text, use_container_width=True):
186
+ st.session_state.tamil_input = text
187
+ st.session_state.creativity = creativity
188
+
189
+ st.divider()
190
+ st.header("விவரங்கள்")
191
+ st.markdown("""
192
+ - **மொழிபெயர்ப்பு மாதிரி**: Facebook NLLB-200 (Tamil → English)
193
+ - **உரை உருவாக்கம்**: GPT-2 Medium
194
+ - **பட உருவாக்கம்**: Stable Diffusion v1.5
195
+ """)
196
+ st.divider()
197
+ st.markdown("""
198
+ **அறிவுறுத்தல்கள்**:
199
+ 1. தமிழில் உங்கள் யோசனையை உள்ளிடவும்
200
+ 2. படைப்புத்திறன் அளவை சரிசெய்யவும் (1-10)
201
+ 3. "உருவாக்கு" பொத்தானை அழுத்தவும்
202
+ 4. உங்கள் படம் மற்றும் உரை விளைவுகளைப் பாருங்கள்!
203
+ """)
204
+
205
+ # Main content
206
+ with st.form("input_form"):
207
+ col1, col2 = st.columns([3, 1])
208
+
209
+ with col1:
210
+ tamil_input = st.text_area(
211
+ "தமிழ் உள்ளீடு",
212
+ value=st.session_state.tamil_input,
213
+ placeholder="உதாரணம்: பனி படர்ந்த குளிர்காலத்தில் வெப்பமான காபி குடிக்கும் பழங்குடி பெண்",
214
+ height=150
215
  )
216
+
217
+ with col2:
218
+ creativity = st.slider(
219
+ "படைப்பாற்றல் நிலை",
220
+ min_value=1, max_value=10, value=st.session_state.creativity, step=1,
221
+ help="அதிக எண் = அதிக புதுமை ஆனால் குறைந்த துல்லியம்"
222
+ )
223
+ submit_btn = st.form_submit_button("உருவாக்கு", use_container_width=True)
224
+ clear_btn = st.form_submit_button("துடைத்து துவக்கவும்", use_container_width=True)
225
 
226
+ # Process inputs
227
+ if submit_btn and tamil_input:
228
+ with st.spinner("உருவாக்கம் நடந்து கொண்டிருக்கிறது..."):
229
+ english_text, creative_text, image, proc_time, error = process_content(tamil_input, creativity)
230
+
231
+ # Save outputs to session state
232
+ st.session_state.outputs.append({
233
+ "tamil_input": tamil_input,
234
+ "english_text": english_text,
235
+ "creative_text": creative_text,
236
+ "image": image,
237
+ "proc_time": proc_time
238
+ })
239
+
240
+ # Display results
241
+ st.subheader("முடிவுகள்")
242
+
243
+ col1, col2 = st.columns(2)
244
+
245
+ with col1:
246
+ st.text_area("ஆங்கில மொழிபெயர்ப்பு", value=english_text, height=100, disabled=True)
247
+ st.text_area("படைப்பு உரை", value=creative_text, height=150, disabled=True)
248
+ if proc_time:
249
+ st.info(proc_time)
250
+
251
+ with col2:
252
+ if image:
253
+ st.image(image, caption="உருவாக்கப்பட்ட படம்", use_column_width=True)
254
+
255
+ # Add download button
256
+ buf = io.BytesIO()
257
+ image.save(buf, format="PNG")
258
+ byte_im = buf.getvalue()
259
+ st.download_button(
260
+ label="படத்தை பதிவிறக்குக",
261
+ data=byte_im,
262
+ file_name="tamil_ai_image.png",
263
+ mime="image/png",
264
+ use_container_width=True
265
+ )
266
+
267
+ if error:
268
+ st.error(error)
269
+
270
+ # Clear button functionality
271
+ if clear_btn:
272
+ st.session_state.tamil_input = ""
273
+ st.session_state.creativity = 7
274
+ st.session_state.outputs = []
275
+ st.experimental_rerun()
276
+
277
+ # Display history
278
+ if st.session_state.outputs:
279
+ st.divider()
280
+ st.subheader("முந்தைய உருவாக்கங்கள்")
281
+
282
+ for i, output in enumerate(reversed(st.session_state.outputs)):
283
+ with st.expander(f"உருவாக்கம் #{len(st.session_state.outputs)-i}: {output['tamil_input'][:50]}..."):
284
+ col1, col2 = st.columns(2)
285
+
286
+ with col1:
287
+ st.text_area(f"மொழிபெயர்ப்பு #{len(st.session_state.outputs)-i}",
288
+ value=output['english_text'], height=100, disabled=True, key=f"eng_{i}")
289
+ st.text_area(f"படைப்பு உரை #{len(st.session_state.outputs)-i}",
290
+ value=output['creative_text'], height=150, disabled=True, key=f"text_{i}")
291
+ if output.get('proc_time'):
292
+ st.info(output['proc_time'])
293
+
294
+ with col2:
295
+ if output['image']:
296
+ st.image(output['image'], caption="உருவாக்கப்பட்ட படம்", use_column_width=True)
297
+ buf = io.BytesIO()
298
+ output['image'].save(buf, format="PNG")
299
+ byte_im = buf.getvalue()
300
+ st.download_button(
301
+ label=f"படத்தை பதிவிறக்குக #{len(st.session_state.outputs)-i}",
302
+ data=byte_im,
303
+ file_name=f"tamil_ai_image_{len(st.session_state.outputs)-i}.png",
304
+ mime="image/png",
305
+ use_container_width=True,
306
+ key=f"download_{i}"
307
+ )