File size: 2,050 Bytes
75b292f
 
666e16a
 
 
 
 
 
3b844d5
666e16a
3b844d5
6f13ba7
3b844d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6804466
 
 
 
 
 
3b844d5
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Corrected app.py file without `!pip` commands

from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
from transformers import MBartForConditionalGeneration, MBart50Tokenizer
import gradio as gr
import requests
import io
from PIL import Image
import os  # Import os to access environment variables

# Load the models and tokenizers
model_name = "facebook/mbart-large-50-many-to-one-mmt"
tokenizer = MBart50Tokenizer.from_pretrained(model_name)
model = MBartForConditionalGeneration.from_pretrained(model_name)

# Use the Hugging Face API key from environment variables
API_URL = "https://api-inference.huggingface.co/models/ZB-Tech/Text-to-Image"
headers = {"Authorization": f"Bearer {os.getenv('HF_API_KEY')}"}

# Define the function to translate Tamil text and generate an image
def translate_and_generate_image(tamil_text):
    # Step 1: Translate Tamil text to English
    tokenizer.src_lang = "ta_IN"
    inputs = tokenizer(tamil_text, return_tensors="pt")
    translated_tokens = model.generate(**inputs, forced_bos_token_id=tokenizer.lang_code_to_id["en_XX"])
    translated_text = tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)[0]

    # Step 2: Use the translated English text to generate an image
    def query(payload):
        response = requests.post(API_URL, headers=headers, json=payload)
        return response.content

    image_bytes = query({"inputs": translated_text})
    image = Image.open(io.BytesIO(image_bytes))

    return translated_text, image

# Gradio interface setup
iface = gr.Interface(
    fn=translate_and_generate_image,
    inputs=gr.Textbox(lines=2, placeholder="Enter Tamil text here..."),
    outputs=[gr.Textbox(label="Translated English Text"), gr.Image(label="Generated Image")],
    title="Tamil to English Translation and Image Generation",
    description="Translate Tamil text to English using Facebook's mbart-large-50 model and generate an image using the translated text as the prompt.",
)

# Launch Gradio app with a shareable link
iface.launch(share=True)