24Sureshkumar commited on
Commit
ddb377a
·
verified ·
1 Parent(s): 539c484

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -49
app.py CHANGED
@@ -1,123 +1,119 @@
1
  # app.py
 
2
  import gradio as gr
3
- from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
4
  from diffusers import StableDiffusionPipeline
5
  import torch
6
  import re
7
  import os
8
  from huggingface_hub import login
9
 
 
10
  HF_TOKEN = os.environ.get("HF_TOKEN")
11
  if not HF_TOKEN:
12
  raise ValueError("Hugging Face token not found in environment variables!")
13
-
14
- # Authenticate with Hugging Face Hub
15
  else:
16
  login(token=HF_TOKEN)
17
 
18
- # Initialize models
19
  def load_models():
20
- # Load translation model (NLLB - best for Tamil)
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 # Token added here
28
  )
29
-
30
- # Text generation pipeline
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 # Token added here
36
  )
37
-
38
- # Image generation pipeline
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 # Token added here
45
  ).to("cuda")
46
  else:
47
  image_pipe = StableDiffusionPipeline.from_pretrained(
48
  "runwayml/stable-diffusion-v1-5",
49
- use_auth_token=HF_TOKEN # Token added here
50
  )
51
-
52
  return translator, text_generator, image_pipe
53
 
54
- # Load models 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
  def clean_text(text):
61
- """Remove special characters and truncate to complete sentences"""
62
- cleaned = re.split(r'(?<=[.!?])\s+', text)[0]
63
- return re.sub(r'[^a-zA-Z0-9,.!?\'"\- ]+', '', cleaned).strip()
64
 
 
65
  def process_content(tamil_input, creativity_level):
66
- outputs = {}
67
- error = ""
68
-
69
  try:
70
- # Translate Tamil to English
71
  translation_result = translator(tamil_input)
72
  english_text = translation_result[0]['translation_text']
73
- outputs["translation"] = english_text
74
-
75
- # Generate image
76
  image = image_pipe(
77
- english_text,
78
  guidance_scale=creativity_level,
79
  num_inference_steps=30
80
  ).images[0]
81
- outputs["image"] = image
82
-
83
- # Generate creative text
84
  creative_output = text_generator(
85
  f"Create creative content about: {english_text}",
86
  max_length=150,
87
- temperature=creativity_level/10,
88
  num_return_sequences=1
89
  )
90
- outputs["creative_text"] = clean_text(creative_output[0]['generated_text'])
91
-
92
  except Exception as e:
93
- error = f"⚠️ Error: {str(e)}"
94
-
95
- return outputs, error
96
 
97
  # Gradio UI
98
  with gr.Blocks(theme=gr.themes.Soft()) as app:
99
  gr.Markdown("# 🌐 தமிழ் உரை முதல் பட உருவாக்கம் (Tamil to Image Generator)")
100
  gr.Markdown("தமிழில் உள்ளீடு செய்து → ஆங்கில மொழிபெயர்ப்பு + AI உருவம் + படைப்பு உரை பெறவும்")
101
-
102
  with gr.Row():
103
  with gr.Column():
104
  tamil_input = gr.Textbox(
105
- label="தமிழ் உள்ளீடு",
106
- placeholder="உங்கள் உரையை இங்கே உள்ளிடவும்...",
107
  lines=3
108
  )
109
  creativity = gr.Slider(
110
- label="படைப்பாற்றல் நிலை",
111
  minimum=1, maximum=10, value=7, step=1
112
  )
113
  submit_btn = gr.Button("உருவாக்கு")
114
-
115
  with gr.Column():
116
  translation_box = gr.Textbox(label="ஆங்கில மொழிபெயர்ப்பு")
117
  creative_output = gr.Textbox(label="படைப்பு உரை", lines=3)
118
  image_output = gr.Image(label="உருவாக்கப்பட்ட படம்")
119
  error_output = gr.Textbox(label="பிழை செய்திகள்", visible=True)
120
-
 
121
  examples = gr.Examples(
122
  examples=[
123
  ["கடலின் அடியில் மறைந்திருக்கும் பழைய நகரம்", 8],
@@ -126,24 +122,24 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
126
  ],
127
  inputs=[tamil_input, creativity]
128
  )
129
-
130
- # Clear inputs button
131
  clear_btn = gr.Button("துடைத்து துவக்கவும்")
132
-
133
  def clear_all():
134
  return "", "", "", None, ""
135
-
136
  submit_btn.click(
137
  fn=process_content,
138
  inputs=[tamil_input, creativity],
139
- outputs=[{"translation": translation_box, "creative_text": creative_output, "image": image_output}, error_output]
140
  )
141
-
142
  clear_btn.click(
143
  fn=clear_all,
144
  inputs=[],
145
  outputs=[tamil_input, translation_box, creative_output, image_output, error_output]
146
  )
147
 
 
148
  if __name__ == "__main__":
149
- app.launch()
 
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):
62
+ cleaned = re.sub(r'[^a-zA-Z0-9,.!?\'"\- ]+', '', text).strip()
63
+ sentences = re.split(r'(?<=[.!?])\s+', cleaned)
64
+ return ' '.join(sentences[:2]) # return first 2 sentences
65
 
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],
 
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()