|
import os |
|
from langchain.llms import OpenAI |
|
from langchain.chat_models import ChatOpenAI |
|
from langchain.prompts import PromptTemplate |
|
import gradio as gr |
|
import random |
|
import string |
|
|
|
|
|
|
|
openai_api_key = os.environ["OPEN_API_KEY"] |
|
|
|
|
|
llm = OpenAI(openai_api_key= openai_api_key, model_name="gpt-3.5-turbo", temperature= 0.0) |
|
|
|
template = """Translate the text. You are a very professional translator. Translate the given sentence into {target}\ |
|
|
|
Text: {query} |
|
|
|
Translated text: """ |
|
|
|
prompt_template = PromptTemplate( |
|
input_variables=["target", "query"], |
|
template=template |
|
) |
|
|
|
|
|
def random_punctuation(text): |
|
|
|
punctuation = "_" |
|
new_text = "" |
|
for word in text.split(): |
|
if (len(word) > 3) or (word == 'غزة') or (word == 'غزه'): |
|
result = "" |
|
middle = len(word) // 2 |
|
middel_of_text = word[:middle] + random.choice(punctuation) + word[middle:] |
|
|
|
result = '*' + middel_of_text + "*" |
|
new_text += result + " " |
|
else: |
|
new_text += word + " " |
|
return new_text.strip() |
|
|
|
def MT(query, target): |
|
translated_text = llm(prompt_template.format(target = target, query=query)) |
|
return translated_text |
|
|
|
def gradio_func(query, target, style): |
|
if len(query) > 400: |
|
return "Please make your text shorter than upove | الرجاء تصغير النص للترجمه" |
|
translated_text = MT(query, target) |
|
if style == "Translate | الترجمه": |
|
return translated_text |
|
elif style == "Change the text | تغيير النص": |
|
return random_punctuation(text) |
|
else: |
|
return random_punctuation(translated_text) |
|
|
|
|
|
|
|
gr.close_all() |
|
demo = gr.Interface(fn=gradio_func, |
|
inputs=[ |
|
gr.Textbox(label="Your Text | النص الخاص بك", lines= 4), |
|
|
|
gr.Radio(["Arabic", "English", "Mandarin Chinese", "Spanish", "Hindi", "Bengali", "Portuguese", "Russian", "Japanese", "French"], |
|
label="Languages | اللغات", |
|
info= "Which language you want to translate? | ما هي اللغه التي تود الترجمه إليها؟"), |
|
|
|
gr.Radio(["Translate | الترجمه", |
|
"Change the text | تغيير النص", |
|
"Translate and change the text | الترجمه و تغير النص معاً"], |
|
label="What you want? | ماذا تريد؟") |
|
], |
|
outputs=[ |
|
gr.Textbox(label="Generated Text", lines=4) |
|
|
|
], |
|
title="Text Translation And Formatter For Palestinian Case, Support Palestine 🇵🇸.", |
|
description="## Flag, for any erroneous output.", |
|
examples= [ |
|
["سكان غزة يتعرضون لإبادة جماعية وسط أنظار العالم الصامت الذي لا يمنع عدوان وإرهاب إسرائيل!","Translate | الترجمه"], |
|
["سكان غزة يتعرضون لإبادة جماعية وسط أنظار العالم الصامت الذي لا يمنع عدوان وإرهاب إسرائيل!","Change the text | تغيير النص"], |
|
["سكان غزة يتعرضون لإبادة جماعية وسط أنظار العالم الصامت الذي لا يمنع عدوان وإرهاب إسرائيل!","Translate and change the text | الترجمه و تغير النص معاً"] |
|
] |
|
) |
|
demo.launch(share=True) |