IS361Group4 commited on
Commit
2d4f7d4
·
verified ·
1 Parent(s): 0ab1f67

Update modules/translator.py

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