Spaces:
Runtime error
Runtime error
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from langchain_core.pydantic_v1 import BaseModel, Field
|
| 4 |
+
from langchain.prompts import HumanMessagePromptTemplate, ChatPromptTemplate
|
| 5 |
+
from langchain.output_parsers import PydanticOutputParser
|
| 6 |
+
from langchain_openai import ChatOpenAI
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# with open('openai_api_key.txt') as f:
|
| 10 |
+
# api_key = f.read()
|
| 11 |
+
|
| 12 |
+
# os.environ['OPENAI_API_KEY'] = api_key
|
| 13 |
+
|
| 14 |
+
chat = ChatOpenAI()
|
| 15 |
+
|
| 16 |
+
class TextTranslator(BaseModel):
|
| 17 |
+
output: str = Field(description="Python string containing the output text translated in the desired language")
|
| 18 |
+
|
| 19 |
+
output_parser = PydanticOutputParser(pydantic_object=TextTranslator)
|
| 20 |
+
format_instructions = output_parser.get_format_instructions()
|
| 21 |
+
|
| 22 |
+
def text_translator(input_text : str, language : str) -> str:
|
| 23 |
+
human_template = """Enter the text that you want to translate:
|
| 24 |
+
{input_text}, and enter the language that you want it to translate to {language}. {format_instructions}"""
|
| 25 |
+
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
|
| 26 |
+
|
| 27 |
+
chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])
|
| 28 |
+
|
| 29 |
+
prompt = chat_prompt.format_prompt(input_text = input_text, language = language, format_instructions = format_instructions)
|
| 30 |
+
|
| 31 |
+
messages = prompt.to_messages()
|
| 32 |
+
|
| 33 |
+
response = chat(messages = messages)
|
| 34 |
+
|
| 35 |
+
output = output_parser.parse(response.content)
|
| 36 |
+
|
| 37 |
+
output_text = output.output
|
| 38 |
+
|
| 39 |
+
return output_text
|
| 40 |
+
|
| 41 |
+
# Interface
|
| 42 |
+
with gr.Blocks() as demo:
|
| 43 |
+
gr.HTML("<h1 align = 'center'> Text Translator </h1>")
|
| 44 |
+
gr.HTML("<h4 align = 'center'> Translate to any language </h4>")
|
| 45 |
+
|
| 46 |
+
inputs = [gr.Textbox(label = "Enter the text that you want to translate"), gr.Textbox(label = "Enter the language that you want it to translate to", placeholder = "Example : Hindi,French,Bengali,etc")]
|
| 47 |
+
generate_btn = gr.Button(value = 'Generate')
|
| 48 |
+
outputs = [gr.Textbox(label = "Translated text")]
|
| 49 |
+
generate_btn.click(fn = text_translator, inputs= inputs, outputs = outputs)
|
| 50 |
+
|
| 51 |
+
if __name__ == '__main__':
|
| 52 |
+
demo.launch()
|