Spaces:
Sleeping
Sleeping
Create test.py
Browse files
test.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from langchain.chains import LLMChain
|
| 3 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 4 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 5 |
+
import os
|
| 6 |
+
import google.generativeai as genai
|
| 7 |
+
|
| 8 |
+
api_key = os.getenv("GEMINI_KEY2")
|
| 9 |
+
|
| 10 |
+
# Define the Chat Prompt Template
|
| 11 |
+
prompt = ChatPromptTemplate.from_messages(
|
| 12 |
+
[
|
| 13 |
+
(
|
| 14 |
+
"system",
|
| 15 |
+
"You are a helpful assistant that translates {input_language} to {output_language}.",
|
| 16 |
+
),
|
| 17 |
+
("human", "{input}"),
|
| 18 |
+
]
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# Initialize the Google Generative AI model
|
| 22 |
+
llm = ChatGoogleGenerativeAI(
|
| 23 |
+
model="gemini-1.5-pro",
|
| 24 |
+
temperature=0.5,
|
| 25 |
+
max_tokens=None,
|
| 26 |
+
timeout=None,
|
| 27 |
+
max_retries=2,
|
| 28 |
+
api_key=api_key
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
# Define the chain for translation
|
| 32 |
+
translation_chain = LLMChain(prompt=prompt, llm=llm)
|
| 33 |
+
|
| 34 |
+
# Function to translate text
|
| 35 |
+
def translate_text(input_text, input_language, output_language):
|
| 36 |
+
try:
|
| 37 |
+
response = translation_chain({"input": input_text, "input_language": input_language, "output_language": output_language})
|
| 38 |
+
translation = response["text"].strip()
|
| 39 |
+
except Exception as e:
|
| 40 |
+
st.error(f"Error translating text to {output_language}: {e}")
|
| 41 |
+
translation = f"Sorry, we couldn't translate to {output_language} at the moment."
|
| 42 |
+
|
| 43 |
+
return translation
|
| 44 |
+
|
| 45 |
+
# Streamlit UI
|
| 46 |
+
st.title("📝 Text Translation Bot with LangChain and Google Generative AI")
|
| 47 |
+
|
| 48 |
+
# User input
|
| 49 |
+
input_text = st.text_area("Enter text to translate:")
|
| 50 |
+
|
| 51 |
+
# Language choices
|
| 52 |
+
languages = ["Hindi", "Spanish", "German"]
|
| 53 |
+
output_language = st.selectbox("Select output language:", languages)
|
| 54 |
+
|
| 55 |
+
# Generate translation button
|
| 56 |
+
if st.button("Translate"):
|
| 57 |
+
if input_text.strip():
|
| 58 |
+
st.write("Translating text, please wait...")
|
| 59 |
+
translated_text = translate_text(input_text, "English", output_language)
|
| 60 |
+
st.write("### Translated Text")
|
| 61 |
+
st.write(translated_text)
|
| 62 |
+
else:
|
| 63 |
+
st.warning("Please enter some text to translate.")
|