File size: 2,179 Bytes
2d4f7d4
 
 
ccbf51f
2d4f7d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70a3084
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import os
import gradio as gr

from pydantic.v1 import BaseModel, Field
from langchain.prompts import HumanMessagePromptTemplate, ChatPromptTemplate
from langchain.output_parsers import PydanticOutputParser
from langchain_openai import ChatOpenAI

chat = ChatOpenAI()

# Define the Pydantic Model
class TextTranslator(BaseModel):
    output: str = Field(description="Python string containing the output text translated in the desired language")
    
output_parser = PydanticOutputParser(pydantic_object=TextTranslator)
format_instructions = output_parser.get_format_instructions()

def text_translator(input_text : str, language : str) -> str:
    human_template = """Enter the text that you want to translate: 
                {input_text}, and enter the language that you want it to translate to {language}. {format_instructions}"""
    human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
    
    chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])
    
    prompt = chat_prompt.format_prompt(input_text = input_text, language = language, format_instructions = format_instructions)
    
    messages = prompt.to_messages()
    
    response = chat(messages = messages)
    
    output = output_parser.parse(response.content)
    
    output_text = output.output
    
    return output_text

# Interface
def translator_interface():
    with gr.Blocks() as demo:
        gr.HTML("<h1 align = 'center'> Text Translator </h1>")
        gr.HTML("<h4 align = 'center'> Translate to any language </h4>")
        
        with gr.Row():
            input_text = gr.Textbox(label="Enter the text that you want to translate")
            language = gr.Textbox(label="Enter the language that you want it to translate to", placeholder="Example: Hindi, French, Bengali, etc.")
        
        generate_btn = gr.Button(value='Generate')
        output_text = gr.Textbox(label="Translated text")
        
        generate_btn.click(fn=text_translator, inputs=[input_text, language], outputs=output_text)
    
    return demo

# สำหรับแสดง Interface ใน app.py
def get_translator_tab():
    return translator_interface()