Update app.py
Browse files
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 |
-
|
|
|
15 |
else:
|
16 |
login(token=HF_TOKEN)
|
17 |
|
18 |
-
#
|
|
|
|
|
|
|
|
|
19 |
def load_models():
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
-
|
|
|
|
|
55 |
try:
|
56 |
translator, text_generator, image_pipe = load_models()
|
57 |
except Exception as e:
|
58 |
-
|
|
|
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 |
-
|
71 |
-
|
72 |
-
|
|
|
73 |
# Image generation
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
|
|
|
|
|
|
80 |
# Text generation
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
)
|