arulselvi commited on
Commit
a5d604b
·
verified ·
1 Parent(s): a7c6fe9

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +149 -0
README.md ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 gradio as gr
7
+ import torch
8
+
9
+ # Detect if GPU is available
10
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
11
+
12
+ # Load the MarianMT model and tokenizer for translation (Tamil to English)
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)
16
+
17
+ # Load GPT-Neo for creative text generation
18
+ text_generation_model_name = "EleutherAI/gpt-neo-1.3B"
19
+ text_generation_model = AutoModelForCausalLM.from_pretrained(text_generation_model_name).to(device)
20
+ text_generation_tokenizer = AutoTokenizer.from_pretrained(text_generation_model_name)
21
+
22
+ # Add padding token to GPT-Neo tokenizer if not present
23
+ if text_generation_tokenizer.pad_token is None:
24
+ text_generation_tokenizer.add_special_tokens({'pad_token': '[PAD]'})
25
+
26
+ # Ensure pad_token_id is set correctly
27
+ text_generation_model.config.pad_token_id = text_generation_tokenizer.pad_token_id
28
+
29
+ # Set your Hugging Face API key
30
+ os.environ['HF_API_KEY'] = 'api key' # Replace with your actual API key
31
+ api_key = os.getenv('HF_API_KEY')
32
+ if api_key is None:
33
+ raise ValueError("Hugging Face API key is not set. Please set it in your environment.")
34
+
35
+ headers = {"Authorization": f"Bearer {api_key}"}
36
+
37
+ # Define the API URL for image generation (ensure this is a valid inference endpoint)
38
+ API_URL = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-dev"
39
+
40
+ # Query Hugging Face API to generate image with error handling
41
+ def query(payload):
42
+ try:
43
+ response = requests.post(API_URL, headers=headers, json=payload)
44
+ response.raise_for_status() # Raises an HTTPError for bad responses
45
+ return response.content, response.headers # Return both content and headers
46
+ except requests.exceptions.HTTPError as err:
47
+ print(f"HTTP error occurred: {err}")
48
+ except Exception as e:
49
+ print(f"An error occurred: {e}")
50
+ return None, None # Return None for both if there's an error
51
+
52
+ # Translate Tamil text to English
53
+ def translate_text(tamil_text):
54
+ inputs = translation_tokenizer(tamil_text, return_tensors="pt", padding=True, truncation=True).to(device)
55
+ translated_tokens = translation_model.generate(**inputs)
56
+ translation = translation_tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
57
+ return translation
58
+
59
+ # Generate an image based on the translated text with error handling
60
+ def generate_image(prompt):
61
+ image_bytes, headers = query({"inputs": prompt}) # Capture headers as well
62
+
63
+ if image_bytes is None:
64
+ # Return a blank image with error message
65
+ error_img = Image.new('RGB', (300, 300), color=(255, 0, 0))
66
+ d = ImageDraw.Draw(error_img)
67
+ d.text((10, 150), "Image Generation Failed", fill=(255, 255, 255))
68
+ return error_img
69
+
70
+ try:
71
+ # Check if content type is valid for images using headers
72
+ if 'image' not in headers.get('Content-Type', ''):
73
+ raise ValueError("Response content is not an image.")
74
+
75
+ image = Image.open(io.BytesIO(image_bytes))
76
+ return image
77
+ except Exception as e:
78
+ print(f"Error: {e}")
79
+ # Return an error image in case of failure
80
+ error_img = Image.new('RGB', (300, 300), color=(255, 0, 0))
81
+ d = ImageDraw.Draw(error_img)
82
+ d.text((10, 200), "Invalid Image Data", fill=(255, 255, 255))
83
+ return error_img
84
+
85
+ # Generate creative text based on the translated English text
86
+ def generate_creative_text(translated_text):
87
+ inputs = text_generation_tokenizer(translated_text, return_tensors="pt", padding=True, truncation=True).to(device)
88
+ generated_tokens = text_generation_model.generate(**inputs, max_length=100, pad_token_id=text_generation_model.config.pad_token_id)
89
+ creative_text = text_generation_tokenizer.decode(generated_tokens[0], skip_special_tokens=True)
90
+ return creative_text
91
+
92
+ # Function to handle the full workflow
93
+ def translate_generate_image_and_text(tamil_text):
94
+ # Step 1: Translate Tamil to English
95
+ translated_text = translate_text(tamil_text)
96
+
97
+ # Step 2: Generate an image from the translated text
98
+ image = generate_image(translated_text)
99
+
100
+ # Step 3: Generate creative text from the translated text
101
+ creative_text = generate_creative_text(translated_text)
102
+
103
+ return translated_text, creative_text, image
104
+
105
+ # Create a visually appealing Gradio interface
106
+ css = """
107
+ #transart-title {
108
+ font-size: 2.5em;
109
+ font-weight: bold;
110
+ color: #4CAF50;
111
+ text-align: center;
112
+ margin-bottom: 10px;
113
+ }
114
+ #transart-subtitle {
115
+ font-size: 1.25em;
116
+ text-align: center;
117
+ color: #555555;
118
+ margin-bottom: 20px;
119
+ }
120
+ body {
121
+ background-color: #f0f0f5;
122
+ }
123
+ .gradio-container {
124
+ font-family: 'Arial', sans-serif;
125
+ }
126
+ """
127
+
128
+ # Custom HTML for title and subtitle (can be displayed in Markdown)
129
+ title_markdown = """
130
+ # TransArt
131
+ ### Tamil to English Translation, Creative Text & Image Generation
132
+ """
133
+
134
+ # Gradio interface with customized layout and aesthetics
135
+ with gr.Blocks(css=css) as interface:
136
+ gr.Markdown(title_markdown) # Title and subtitle in Markdown
137
+ with gr.Row():
138
+ with gr.Column():
139
+ tamil_input = gr.Textbox(label="Enter Tamil Text", placeholder="Type Tamil text here...", lines=3) # Input for Tamil text
140
+ with gr.Column():
141
+ translated_output = gr.Textbox(label="Translated Text", interactive=False) # Output for translated text
142
+ creative_text_output = gr.Textbox(label="Creative Generated Text", interactive=False) # Output for creative text
143
+ generated_image_output = gr.Image(label="Generated Image") # Output for generated image
144
+
145
+ gr.Button("Generate").click(fn=translate_generate_image_and_text, inputs=tamil_input,
146
+ outputs=[translated_output, creative_text_output, generated_image_output])
147
+
148
+ # Launch the Gradio app
149
+ interface.launch(debug=True, server_name="0.0.0.0")