Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Translation API</title><link rel="stylesheet" href="style.css"><style>/* Add some basic styles for responsiveness and layout */body {font-family: sans-serif;margin: 0;padding: 20px;background-color: #f4f4f4;color: #333;}.container {max-width: 800px;margin: auto;background-color: #fff;padding: 20px;border-radius: 8px;box-shadow: 0 2px 4px rgba(0,0,0,0.1);}h1, h2, h3 {color: #444;}label {display: block;margin-top: 1em;font-weight: bold;}input[type="text"],textarea,select {width: 100%;padding: 8px;margin-top: 5px;border: 1px solid #ccc;border-radius: 4px;box-sizing: border-box; /* Include padding and border in the element's total width and height */}button {background-color: #007bff;color: white;padding: 10px 15px;border: none;border-radius: 4px;cursor: pointer;margin-top: 1em;}button:hover {background-color: #0056b3;}#result {margin-top: 2em;padding: 1em;border: 1px solid #ddd;background-color: #f9f9f9;border-radius: 4px;display: none; /* Hide initially */}#error-message {color: red;margin-top: 1em;}.loading-indicator {display: none; /* Initially hide the loading indicator */margin-top: 1em;color: #007bff;}/* style for the tabs */.tab {overflow: hidden;border: 1px solid #ccc;background-color: #f1f1f1;border-radius: 4px 4px 0 0; /* Rounded top corners */}.tab button {background-color: inherit;float: left;border: none;outline: none;cursor: pointer;padding: 14px 16px;transition: 0.3s;font-size: 17px;border-right: 1px solid #ccc; /* Add a separator between buttons */}.tab button:last-child {border-right: none; /* Remove border from the last button */}.tab button:hover {background-color: #ddd;}.tab button.active {background-color: #ccc;}.tabcontent {display: none;padding: 6px 12px;border: 1px solid #ccc;border-top: none;border-radius: 0 0 4px 4px; /* Rounded bottom corners */}/* Hide by default, use JS to show */#detection-result, #translation-result {display: none;}</style></head><body><div class="container"><h1>Translation and Language Detection API</h1><!-- Tabs --><div class="tab"><button class="tablinks active" onclick="openTab(event, 'translate')">Translate</button><button class="tablinks" onclick="openTab(event, 'detect')">Detect Language</button></div><!-- Translation Tab Content --><div id="translate" class="tabcontent" style="display: block;"> <!-- translate tab set display block --><h2>Translate Text</h2><label for="text-to-translate">Text to Translate:</label><textarea id="text-to-translate" rows="4" placeholder="Enter text here..."></textarea><label for="source-language">Source Language (optional, auto-detect if empty):</label><input type="text" id="source-language" placeholder="e.g., English, en, auto"><label for="target-language">Target Language:</label><input type="text" id="target-language" placeholder="e.g., Spanish, es"><button id="translate-button">Translate</button><div class="loading-indicator" id="translation-loading">Loading...</div><div id="translation-result"><h3>Translation Result:</h3><p><strong>Source Language:</strong> <span id="detected-source-language"></span></p><p><strong>Target Language:</strong> <span id="translation-target-language"></span></p><p><strong>Translated Text:</strong> <span id="translated-text"></span></p></div></div> <!-- end of translation tab --><!-- Detect Language Tab Content --><div id="detect" class="tabcontent"><h2>Detect Language</h2><label for="text-to-detect">Text to Detect:</label><textarea id="text-to-detect" rows="4" placeholder="Enter text here..."></textarea><button id="detect-button">Detect Language</button><div class="loading-indicator" id="detection-loading">Loading...</div><div id="detection-result"><h3>Detection Result:</h3><p><strong>Detected Language:</strong> <span id="detected-language"></span></p><div id="translation-options-container"><h4>Translation Options:</h4><ul id="translation-options-list"></ul></div></div></div> <!-- end of language detection tab--><div id="error-message"></div></div><script>// --- API Base URL (Replace with your actual base URL) ---const API_BASE_URL = 'https://sameernotes-translation-prediction-space.hf.space'; // Replace with your actual hosted URL or localhostconst supportedLanguages = ["Afrikaans","Arabic","Armenian","Azerbaijani","Belarusian","Bosnian","Bulgarian","Catalan","Chinese","Croatian","Czech","Danish","Dutch","English","Estonian","Finnish","French","Galician","German","Greek","Hebrew","Hindi","Hungarian","Icelandic","Indonesian","Italian","Japanese","Kannada","Kazakh","Korean","Latvian","Lithuanian","Macedonian","Malay","Marathi","Maori","Nepali","Norwegian","Persian","Polish","Portuguese","Romanian","Russian","Serbian","Slovak","Slovenian","Spanish","Swahili","Swedish","Tagalog","Tamil","Thai","Turkish","Ukrainian","Urdu","Vietnamese","Welsh",]; // Add all supported languages// --- Helper Functions ---// Function to show error messages.function showError(message) {document.getElementById('error-message').textContent = message;document.getElementById('error-message').style.display = 'block';}// Function to clear error messages.function clearError() {document.getElementById('error-message').textContent = '';document.getElementById('error-message').style.display = 'none';}// Function to open a tab and display the corresponding contentfunction openTab(evt, tabName) {let i, tabcontent, tablinks;tabcontent = document.getElementsByClassName("tabcontent");for (i = 0; i < tabcontent.length; i++) {tabcontent[i].style.display = "none";}tablinks = document.getElementsByClassName("tablinks");for (i = 0; i < tablinks.length; i++) {tablinks[i].className = tablinks[i].className.replace(" active", "");}document.getElementById(tabName).style.display = "block";evt.currentTarget.className += " active";// Hide results when switching tabsdocument.getElementById('translation-result').style.display = 'none';document.getElementById('detection-result').style.display = 'none';}// --- Translation Logic ---document.getElementById('translate-button').addEventListener('click', async () => {const text = document.getElementById('text-to-translate').value;const sourceLanguage = document.getElementById('source-language').value;const targetLanguage = document.getElementById('target-language').value;clearError();document.getElementById('translation-loading').style.display = 'block';document.getElementById('translation-result').style.display = 'none';if (!text) {showError('Please enter text to translate.');document.getElementById('translation-loading').style.display = 'none';return;}if (!targetLanguage) {showError('Please enter the target language.');document.getElementById('translation-loading').style.display = 'none';return;}// Check if the target language is supportedif (!supportedLanguages.includes(targetLanguage) ){showError(`Target language '${targetLanguage}' is not supported. Supported languages are: ${supportedLanguages.join(', ')}`);document.getElementById('translation-loading').style.display = 'none';return;}try {const response = await fetch(`${API_BASE_URL}/translate`, {method: 'POST',headers: {'Content-Type': 'application/json','accept': 'application/json' // Explicitly set the accept header},body: JSON.stringify({text: text,source_language: sourceLanguage || undefined, // Send undefined if emptytarget_language: targetLanguage})});if (!response.ok) {const errorData = await response.json(); // Get error detailsshowError(`Translation failed: ${errorData.detail}`); // Use the 'detail' from the error responsereturn;}const data = await response.json();document.getElementById('detected-source-language').textContent = data.source_language;document.getElementById('translation-target-language').textContent = data.target_language;document.getElementById('translated-text').textContent = data.translated_text;document.getElementById('translation-result').style.display = 'block';} catch (error) {showError(`Error: ${error.message}`);console.error('Error during translation:', error);} finally {document.getElementById('translation-loading').style.display = 'none';}});// --- Language Detection Logic ---document.getElementById('detect-button').addEventListener('click', async () => {const text = document.getElementById('text-to-detect').value;clearError();document.getElementById('detection-loading').style.display = 'block';document.getElementById('detection-result').style.display = 'none'; // Hide previous resultsif (!text) {showError('Please enter text to detect its language.');document.getElementById('detection-loading').style.display = 'none';return;}try {const response = await fetch(`${API_BASE_URL}/detect_language`, {method: 'POST',headers: {'Content-Type': 'application/json','accept': 'application/json',},body: JSON.stringify({ text: text }),});if (!response.ok) {const errorData = await response.json();showError(`Detection failed: ${errorData.detail}`);return;}const data = await response.json();document.getElementById('detected-language').textContent = data.source_language;// Clear previous optionsconst optionsList = document.getElementById('translation-options-list');optionsList.innerHTML = ''; // Important: Clear previous options// Display translation optionsif (data.translation_options && typeof data.translation_options === 'object') {for (const [key, value] of Object.entries(data.translation_options)) {const listItem = document.createElement('li');listItem.textContent = `${key}: ${value}`;optionsList.appendChild(listItem);}document.getElementById('translation-options-container').style.display = 'block'; // Show the container} else {document.getElementById('translation-options-container').style.display = 'none'; // Hide if no options}document.getElementById('detection-result').style.display = 'block';} catch (error) {showError(`Error: ${error.message}`);console.error('Error during language detection:', error);} finally {document.getElementById('detection-loading').style.display = 'none';}});</script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155import osimport re # Import the regular expression modulefrom typing import Listfrom fastapi import FastAPI, HTTPException, statusfrom pydantic import BaseModelimport requestsfrom fastapi.responses import HTMLResponseapp = FastAPI()GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")if not GEMINI_API_KEY:raise ValueError("The GEMINI_API_KEY environment variable is not set.")GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-lite:generateContent?key=" + GEMINI_API_KEYclass TranslationRequest(BaseModel):text: strtarget_language: strsource_language: str = Noneclass TranslationResponse(BaseModel): # For /detect_languagetranslated_text: strsource_language: strtarget_language: str# --- Helper Functions ---def detect_language_and_options(text: str):"""Detects the language and provides translation options."""prompt = f"""Please identify the language of the text provided and then offer translation options as numbered choices (1-5). Use this format: "The text is in [Language]. Choose a language to translate to: 1. [Option 1], 2. [Option 2], 3. [Option 3], 4. [Option 4], 5. [Option 5]"Input Text: {text}"""request_data = {"contents": [{"role": "user","parts": [{"text": prompt}]}]}try:response = requests.post(GEMINI_API_URL, json=request_data)response.raise_for_status()response_json = response.json()try:response_text = response_json['candidates'][0]['content']['parts'][0]['text']source_language = response_text.split("The text is in ")[1].split(".")[0].strip()options_str = response_text.split("Choose a language to translate to:")[1].strip()options_list = [opt.split(". ")[1].strip() for opt in options_str.split(", ")]while len(options_list) < 5:options_list.append("Option Not Available")options_list = options_list[:5]options = {str(i + 1): lang for i, lang in enumerate(options_list)}return source_language, optionsexcept (KeyError, IndexError, AttributeError) as e:raise HTTPException(status_code=500, detail=f"Error parsing Gemini API response: {e}")except requests.exceptions.RequestException as e:raise HTTPException(status_code=500, detail=f"Error communicating with Gemini API: {e}")except Exception as e:raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")def translate_with_gemini(text: str, source_language: str, target_language: str) -> str:"""Translates text, requesting HTML, and removes Markdown code blocks."""prompt = f"""Translate the following text from {source_language} to {target_language}. Return *only* the translated text. Format the response as HTML. If any part of the translated text should be emphasized (like an example or key phrase), use `<strong>` tags around that part. Do not include ANY additional text like 'Here is the translation:' or similar. Only the translated text, formatted as HTML.Text:{text}"""request_data = {"contents": [{"role": "user","parts": [{"text": prompt}]}]}try:response = requests.post(GEMINI_API_URL, json=request_data)response.raise_for_status()response_json = response.json()try:translated_text = response_json['candidates'][0]['content']['parts'][0]['text']# Remove Markdown code blocks (```html ... ```)translated_text = re.sub(r"```html\n?([\s\S]*?)\n?```", r"\1", translated_text).strip()translated_text = re.sub(r"```([\s\S]*?)```", r"\1", translated_text).strip() # Remove plain ``` ... ```return translated_textexcept (KeyError, IndexError) as e:raise HTTPException(status_code=500, detail=f"Error parsing Gemini API response: {e}")except requests.exceptions.RequestException as e:raise HTTPException(status_code=500, detail=f"Error communicating with Gemini API: {e}")except Exception as e:raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")@app.post("/translate", response_class=HTMLResponse, status_code=status.HTTP_200_OK)async def translate(request: TranslationRequest):"""Translates text, returning HTML."""if not request.text:raise HTTPException(status_code=400, detail="Text to translate cannot be empty.")if not request.target_language:raise HTTPException(status_code=400, detail="Target language must be provided.")if request.source_language:source_language = request.source_languageelse:try:source_language, _ = detect_language_and_options(request.text)except HTTPException as e:raise esupported_languages = ["Afrikaans", "Arabic", "Armenian", "Azerbaijani", "Belarusian", "Bosnian", "Bulgarian","Catalan", "Chinese", "Croatian", "Czech", "Danish", "Dutch", "English", "Estonian","Finnish", "French", "Galician", "German", "Greek", "Hebrew", "Hindi", "Hungarian","Icelandic", "Indonesian", "Italian", "Japanese", "Kannada", "Kazakh", "Korean", "Latvian","Lithuanian", "Macedonian", "Malay", "Marathi", "Maori", "Nepali", "Norwegian", "Persian","Polish", "Portuguese", "Romanian", "Russian", "Serbian", "Slovak", "Slovenian", "Spanish","Swahili", "Swedish", "Tagalog", "Tamil", "Thai", "Turkish", "Ukrainian", "Urdu","Vietnamese", "Welsh"]if request.target_language not in supported_languages:raise HTTPException(status_code=400, detail=f"Target language '{request.target_language}' is not supported.")try:translated_html = translate_with_gemini(request.text, source_language, request.target_language)return translated_htmlexcept HTTPException as e:raise eexcept Exception as e:raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")@app.post("/detect_language", status_code=status.HTTP_200_OK)async def detect_language(text: str = ""):"""Detects the language of the input text and provides translation options."""if not text:raise HTTPException(status_code=400, detail="Text to detect cannot be empty.")try:source_language, options = detect_language_and_options(text)return {"source_language": source_language, "translation_options": options}except HTTPException as e:raise eexcept Exception as e:raise HTTPException(status_code=500,detail=f"An unexpected error occurred {e}")
app.py+143-345