Spaces:
Runtime error
Runtime error
File size: 8,828 Bytes
a86a2f9 3ac8fe4 355f55e 3ac8fe4 355f55e 3ac8fe4 355f55e 3ac8fe4 355f55e 3ac8fe4 355f55e 3ac8fe4 355f55e 3ac8fe4 355f55e 3ac8fe4 355f55e 3ac8fe4 355f55e 3ac8fe4 355f55e 3ac8fe4 355f55e 3ac8fe4 355f55e 3ac8fe4 355f55e 3ac8fe4 355f55e | 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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | import gradio as gr
from transformers import pipeline
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize translation pipelines for available models only
translation_models = {}
available_models = {
# English to other languages
"English to Hindi": "Helsinki-NLP/opus-mt-en-hi",
"English to Malayalam": "Helsinki-NLP/opus-mt-en-ml",
"English to Arabic": "Helsinki-NLP/opus-mt-en-ar",
"English to French": "Helsinki-NLP/opus-mt-en-fr",
"English to Spanish": "Helsinki-NLP/opus-mt-en-es",
"English to German": "Helsinki-NLP/opus-mt-en-de",
"English to Chinese": "Helsinki-NLP/opus-mt-en-zh",
# Other languages to English
"Hindi to English": "Helsinki-NLP/opus-mt-hi-en",
"Malayalam to English": "Helsinki-NLP/opus-mt-ml-en",
"Arabic to English": "Helsinki-NLP/opus-mt-ar-en",
"French to English": "Helsinki-NLP/opus-mt-fr-en",
"Spanish to English": "Helsinki-NLP/opus-mt-es-en",
"German to English": "Helsinki-NLP/opus-mt-de-en",
"Chinese to English": "Helsinki-NLP/opus-mt-zh-en",
}
# Load models with error handling
def load_models():
loaded_models = {}
failed_models = []
for name, model_id in available_models.items():
try:
logger.info(f"Loading model: {model_id}")
loaded_models[name] = pipeline(
"translation",
model=model_id,
max_length=400
)
logger.info(f"✅ Successfully loaded: {name}")
except Exception as e:
logger.error(f"❌ Failed to load {name}: {str(e)}")
failed_models.append(name)
if failed_models:
logger.warning(f"Failed to load: {', '.join(failed_models)}")
return loaded_models
# Load all models
translation_models = load_models()
# Translation function with better error handling
def translate_text(text, translation_direction):
if not text.strip():
return "⚠ Please enter some text to translate."
if translation_direction not in translation_models:
return f"❌ Translation model for '{translation_direction}' is not available."
try:
translator = translation_models[translation_direction]
result = translator(text, max_length=400, min_length=30, do_sample=False)
return result[0]['translation_text']
except Exception as e:
logger.error(f"Translation error: {str(e)}")
return f"❌ Translation failed: {str(e)}"
# Custom CSS
custom_css = """
body {
background: linear-gradient(to right, #ff7e5f, #feb47b);
font-family: 'Poppins', sans-serif;
}
.gradio-container {
background-color: white;
border-radius: 20px;
box-shadow: 0 8px 25px rgba(0,0,0,0.15);
padding: 30px;
max-width: 900px !important;
margin: 50px auto;
}
h1 {
text-align: center;
font-size: 2.5em;
color: #2C3E50;
margin-bottom: 10px;
}
.subtitle {
text-align: center;
font-size: 1.1em;
color: #555;
margin-bottom: 30px;
}
.model-status {
text-align: center;
font-size: 0.9em;
color: #27ae60;
margin-bottom: 20px;
}
footer {
text-align: center;
font-size: 0.9em;
color: #555;
margin-top: 25px;
}
button.copy-btn, button.share-btn {
border: none;
padding: 8px 14px;
border-radius: 8px;
cursor: pointer;
margin-top: 8px;
color: white;
font-weight: 500;
}
button.copy-btn { background-color: #3498db; }
button.copy-btn:hover { background-color: #2980b9; }
button.share-btn { background-color: #27ae60; margin-left: 8px; }
button.share-btn:hover { background-color: #1e8449; }
.language-badge {
display: inline-block;
background: #e74c3c;
color: white;
padding: 4px 12px;
border-radius: 20px;
font-size: 0.8em;
margin: 2px;
}
"""
# JS for copy/share buttons
custom_html = """
<script>
function copyTranslation() {
var text = document.querySelector('textarea[aria-label="Translated Text"]').value;
navigator.clipboard.writeText(text);
alert("✅ Translation copied to clipboard!");
}
function shareApp() {
var appLink = "https://huggingface.co/spaces/your-username/translation-app";
navigator.clipboard.writeText(appLink);
alert("🔗 App link copied! You can now share it with others.");
}
</script>
"""
# Gradio UI
with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as app:
gr.HTML("<h1>🌍 Multilingual Translator</h1>")
gr.HTML("""
<div class='subtitle'>
Supports <span class='language-badge'>Hindi</span>
<span class='language-badge'>Malayalam</span>
<span class='language-badge'>Arabic</span>
<span class='language-badge'>French</span>
<span class='language-badge'>Spanish</span>
<span class='language-badge'>German</span>
<span class='language-badge'>Chinese</span>
</div>
""")
# Model status
gr.HTML(f"""
<div class='model-status'>
✅ Loaded {len(translation_models)} out of {len(available_models)} translation models
</div>
""")
with gr.Row():
with gr.Column():
text_input = gr.Textbox(
lines=8,
placeholder="Enter or paste your text here...\n\nExamples:\n• Hello, how are you?\n• नमस्ते, आप कैसे हैं?\n• ഹലോ, സുഖമാണോ?\n• مرحبا، كيف حالك؟",
label="Input Text"
)
translation_direction = gr.Dropdown(
choices=list(translation_models.keys()),
label="Translation Direction",
value="English to Hindi" if "English to Hindi" in translation_models else list(translation_models.keys())[0],
info="Choose the language pair for translation"
)
translate_button = gr.Button("🚀 Translate Text", variant="primary", size="lg")
output_text = gr.Textbox(
label="Translated Text",
lines=8,
placeholder="Your translation will appear here..."
)
# Quick action buttons
with gr.Row():
gr.HTML("""
<div style='text-align:center; width:100%'>
<button class='copy-btn' onclick='copyTranslation()'>📋 Copy Translation</button>
<button class='share-btn' onclick='shareApp()'>🔗 Share this App</button>
</div>
""")
# Examples section
gr.Markdown("### 📚 Try These Examples")
# Create examples based on available models
example_data = []
if "English to Hindi" in translation_models:
example_data.append(["Hello, how are you? What is your name?", "English to Hindi"])
if "Hindi to English" in translation_models:
example_data.append(["नमस्ते, मैं ठीक हूँ। आपका क्या नाम है?", "Hindi to English"])
if "English to Malayalam" in translation_models:
example_data.append(["Good morning, have a nice day", "English to Malayalam"])
if "Malayalam to English" in translation_models:
example_data.append(["സുപ്രഭാതം, ഒരു നല്ല ദിനം", "Malayalam to English"])
if "English to Arabic" in translation_models:
example_data.append(["Welcome to our application", "English to Arabic"])
if "Arabic to English" in translation_models:
example_data.append(["مرحبا بكم في تطبيقنا", "Arabic to English"])
if "English to French" in translation_models:
example_data.append(["This is a wonderful translation tool", "English to French"])
if "French to English" in translation_models:
example_data.append(["Bonjour, comment allez-vous aujourd'hui?", "French to English"])
# Display examples in a grid
with gr.Row():
for i, (text, direction) in enumerate(example_data[:4]):
with gr.Column():
gr.Examples(
examples=[[text, direction]],
inputs=[text_input, translation_direction],
label=f"Example {i+1}"
)
with gr.Row():
for i, (text, direction) in enumerate(example_data[4:8]):
with gr.Column():
gr.Examples(
examples=[[text, direction]],
inputs=[text_input, translation_direction],
label=f"Example {i+5}"
)
# Connect the function
translate_button.click(
translate_text,
inputs=[text_input, translation_direction],
outputs=output_text
)
gr.HTML("<footer>Made with ❤ by <b>STEPHY MARY MATHEW</b> | Multilingual Translation Project</footer>")
gr.HTML(custom_html)
if __name__ == "__main__":
app.launch() |