Edisonpaul commited on
Commit
fa17bf7
·
verified ·
1 Parent(s): d00fda6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +162 -0
app.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import base64
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 torch
9
+
10
+ # Detect if GPU is available
11
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
12
+
13
+ # Load the MarianMT model and tokenizer for translation (Tamil to English)
14
+ model_name = "Helsinki-NLP/opus-mt-mul-en"
15
+ translation_model = MarianMTModel.from_pretrained(model_name).to(device)
16
+ translation_tokenizer = MarianTokenizer.from_pretrained(model_name, clean_up_tokenization_spaces=True)
17
+
18
+ # Set padding token for the translation tokenizer
19
+ translation_tokenizer.pad_token = translation_tokenizer.eos_token
20
+
21
+ # Load GPT-Neo for creative text generation
22
+ text_generation_model_name = "EleutherAI/gpt-neo-1.3B"
23
+ text_generation_model = AutoModelForCausalLM.from_pretrained(text_generation_model_name).to(device)
24
+ text_generation_tokenizer = AutoTokenizer.from_pretrained(text_generation_model_name, clean_up_tokenization_spaces=True)
25
+
26
+ # Set padding token for the text generation tokenizer
27
+ text_generation_tokenizer.pad_token = text_generation_tokenizer.eos_token
28
+
29
+ # Retrieve Hugging Face API key from environment variable
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
37
+ API_URL = "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4"
38
+
39
+ # Unsplash API for background images
40
+ UNSPLASH_URL = "https://api.unsplash.com/photos/random"
41
+ UNSPLASH_API_KEY = "YOUR_UNSPLASH_API_KEY" # Replace with your Unsplash API key
42
+
43
+
44
+ # Function to fetch a random wallpaper from Unsplash
45
+ def fetch_random_wallpaper():
46
+ response = requests.get(UNSPLASH_URL, headers={"Authorization": f"Client-ID {UNSPLASH_API_KEY}"})
47
+ if response.status_code == 200:
48
+ data = response.json()
49
+ image_url = data['urls']['full']
50
+ return image_url
51
+ else:
52
+ st.error("Failed to fetch wallpaper from Unsplash.")
53
+ return None
54
+
55
+ # Function to set background image
56
+ def set_background_image(image_url):
57
+ if image_url is not None:
58
+ # Fetch the image from the URL
59
+ image_bytes = requests.get(image_url).content
60
+ b64 = base64.b64encode(image_bytes).decode()
61
+ # Set the CSS style to set the background image
62
+ st.markdown(
63
+ f"""
64
+ <style>
65
+ .stApp {{
66
+ background-image: url(data:image/png;base64,{b64});
67
+ background-size: cover;
68
+ background-position: center;
69
+ height: 100vh;
70
+ width: 100vw;
71
+ }}
72
+ </style>
73
+ """,
74
+ unsafe_allow_html=True
75
+ )
76
+
77
+ # Query Hugging Face API to generate image with error handling
78
+ def query(payload):
79
+ try:
80
+ response = requests.post(API_URL, headers=headers, json=payload)
81
+ response.raise_for_status() # Raise an error for bad status codes
82
+ return response.content
83
+ except requests.exceptions.RequestException as e:
84
+ st.error(f"API call failed: {e}")
85
+ return None
86
+
87
+ # Translate Tamil text to English
88
+ def translate_text(tamil_text):
89
+ inputs = translation_tokenizer(tamil_text, return_tensors="pt", padding=True, truncation=True).to(device)
90
+ translated_tokens = translation_model.generate(**inputs)
91
+ translation = translation_tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
92
+ return translation
93
+
94
+ # Generate an image based on the translated text with error handling
95
+ def generate_image(prompt):
96
+ image_bytes = query({"inputs": prompt})
97
+
98
+ if image_bytes is None:
99
+ # Return a blank image with an error message
100
+ error_img = Image.new('RGB', (300, 300), color=(255, 0, 0))
101
+ d = ImageDraw.Draw(error_img)
102
+ d.text((10, 150), "Image Generation Failed", fill=(255, 255, 255))
103
+ return error_img
104
+
105
+ try:
106
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
107
+ return image
108
+ except Exception as e:
109
+ st.error(f"Error loading image: {e}")
110
+ # Return an error image in case of failure
111
+ error_img = Image.new('RGB', (300, 300), color=(255, 0, 0))
112
+ d = ImageDraw.Draw(error_img)
113
+ d.text((10, 150), "Invalid Image Data", fill=(255, 255, 255))
114
+ return error_img
115
+
116
+ # Generate creative text based on the translated English text
117
+ def generate_creative_text(translated_text):
118
+ inputs = text_generation_tokenizer(translated_text, return_tensors="pt", padding=True, truncation=True).to(device)
119
+ generated_tokens = text_generation_model.generate(**inputs, max_length=100)
120
+ creative_text = text_generation_tokenizer.decode(generated_tokens[0], skip_special_tokens=True)
121
+ return creative_text
122
+
123
+ # Function to handle the full workflow
124
+ def translate_generate_image_and_text(tamil_text):
125
+ # Step 1: Translate Tamil to English
126
+ translated_text = translate_text(tamil_text)
127
+
128
+ # Step 2: Generate an image from the translated text
129
+ image = generate_image(translated_text)
130
+
131
+ # Step 3: Generate creative text from the translated text
132
+ creative_text = generate_creative_text(translated_text)
133
+
134
+ return translated_text, creative_text, image
135
+
136
+ # Streamlit app title and subtitle
137
+ st.markdown("<h1 style='text-align: center;'>A Multimodal Application</h1>", unsafe_allow_html=True)
138
+ st.markdown("<h3 style='text-align: center;'>Language Translation and Image Synthesis</h3>", unsafe_allow_html=True)
139
+
140
+ # Fetch and set random wallpaper from Unsplash
141
+ image_url = fetch_random_wallpaper()
142
+ set_background_image(image_url)
143
+
144
+ # User input for Tamil text
145
+ tamil_input = st.text_area("Enter Tamil Text", height=150)
146
+
147
+ # Button to generate translation, creative text, and image
148
+ if st.button("Generate"):
149
+ if tamil_input:
150
+ with st.spinner("Generating..."):
151
+ translated_output, creative_text_output, generated_image_output = translate_generate_image_and_text(tamil_input)
152
+
153
+ st.subheader("Translated Text")
154
+ st.write(translated_output)
155
+
156
+ st.subheader("Creative Generated Text")
157
+ st.write(creative_text_output)
158
+
159
+ st.subheader("Generated Image")
160
+ st.image(generated_image_output, caption="Generated Image", use_column_width=True)
161
+ else:
162
+ st.warning("Please enter some Tamil text.")