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