Spaces:
Sleeping
Sleeping
| import os | |
| import json | |
| import gradio as gr | |
| import requests | |
| LANGUAGES = ['Bengali', 'Hindi', 'Tamil', 'English', 'German', 'Telugu', 'French', 'Spanish', 'Kannada', 'Dutch'] | |
| def get_alternate_text(text, language): | |
| ENDPOINT = "https://api.openai.com/v1/chat/completions" | |
| headers = { | |
| "Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}", | |
| "Content-Type": "application/json", | |
| } | |
| system_prompt = f"Please rephrase this text in {language} in lesser words in a manner that it is natural sounding, very concise but without any key information loss. Give 3 such texts separated by new line. Return only the texts without any numbering or bullets." | |
| prompt = f"""Text: | |
| --- | |
| {text} | |
| --- | |
| """ | |
| payload = { | |
| "model": "gpt-3.5-turbo", | |
| "messages": [ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": prompt} | |
| ], | |
| "temperature": 0.4 | |
| } | |
| response = requests.post(ENDPOINT, data=json.dumps(payload), headers=headers) | |
| resp_text = None | |
| retries = 0 | |
| while resp_text is None and retries < 5: | |
| try: | |
| resp_text = response.json().get('choices')[0]['message']['content'].strip("\n").replace('"', "") | |
| except Exception as e: | |
| print(e) | |
| response = requests.post(ENDPOINT, data=json.dumps(payload), headers=headers) | |
| retries += 1 | |
| resp_text = None | |
| continue | |
| if resp_text is None: | |
| return "Error. Please refresh and try", None | |
| texts = list(filter(lambda x: len(x.strip()) > 0, resp_text.split("\n"))) | |
| counts = list(map(lambda x: len(x.split()), texts)) | |
| return len(text.split()), {"data": list(zip(texts, counts)), "headers": ["Alternatives", "Word Count"]} | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# Deepsync Text Rephraser") | |
| language = gr.Dropdown(LANGUAGES, value="Spanish", label="Language") | |
| text = gr.Textbox(lines=4, label="Text") | |
| submit = gr.Button(label="Submit") | |
| dataframe = gr.Dataframe(wrap=True, label="Alternate Rephrasings") | |
| word_count = gr.Textbox(lines=1, label="Word Count") | |
| submit.click(get_alternate_text, [text, language], [word_count, dataframe]) | |
| if __name__=="__main__": | |
| demo.launch( | |
| auth=(os.environ.get('AUTH_USERNAME'), os.environ.get('AUTH_PASSWORD')) | |
| ) |