Rawiwan1912 commited on
Commit
66cca75
·
verified ·
1 Parent(s): 921a466

Update translator.py

Browse files
Files changed (1) hide show
  1. translator.py +35 -0
translator.py CHANGED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pydantic import BaseModel, Field
3
+ from langchain.prompts import HumanMessagePromptTemplate, ChatPromptTemplate
4
+ from langchain.output_parsers import PydanticOutputParser
5
+ from langchain_openai import ChatOpenAI
6
+
7
+ chat = ChatOpenAI()
8
+
9
+ # Define the Pydantic Model (updated for Pydantic v2)
10
+ class TextTranslator(BaseModel):
11
+ output: str = Field(description="Python string containing the output text translated in the desired language")
12
+
13
+ # Use PydanticOutputParser (no need for response_schemas)
14
+ output_parser = PydanticOutputParser(pydantic_object=TextTranslator)
15
+
16
+ def text_translator(input_text: str, language: str) -> str:
17
+ human_template = """Enter the text that you want to translate:
18
+ {input_text}, and enter the language that you want it to translate to {language}."""
19
+ human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
20
+ chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])
21
+ prompt = chat_prompt.format_prompt(input_text=input_text, language=language)
22
+ messages = prompt.to_messages()
23
+ response = chat(messages=messages)
24
+
25
+ # Use output_parser to parse the response
26
+ output = output_parser.parse(response.content)
27
+ return output.output
28
+
29
+ def text_translator_ui():
30
+ gr.Markdown("### Text Translator\nTranslate text into any language using AI.")
31
+ input_text = gr.Textbox(label="Enter the text that you want to translate")
32
+ input_lang = gr.Textbox(label="Enter the language that you want it to translate to", placeholder="Example: Hindi, French, Bengali, etc.")
33
+ output_text = gr.Textbox(label="Translated text")
34
+ translate_button = gr.Button("Translate")
35
+ translate_button.click(fn=text_translator, inputs=[input_text, input_lang], outputs=output_text)