import os # import openai from dotenv import dotenv_values from langchain.llms import OpenAI from langchain.chat_models import ChatOpenAI from langchain import PromptTemplate import gradio as gr import random import string env_values = dotenv_values("./env.env") openai_api_key = env_values['OPEN_API_KEY'] # openai_api_key = "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" 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 = "#$%&*+-<=>@^_~" 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 = random.choice(punctuation) + middel_of_text + random.choice(punctuation) 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 Text Formatter For Palestinian Case, Support Palestine 🇵🇸.", description="## Flag, for any errorneous output.", ) demo.launch(share=True)