File size: 2,336 Bytes
15e5321
 
 
 
 
 
 
 
 
 
 
 
 
 
5599d7e
15e5321
 
 
 
 
 
 
 
 
 
 
 
 
 
5599d7e
595c50d
 
15e5321
5599d7e
15e5321
 
 
595c50d
f28e10e
15e5321
f13775c
595c50d
5599d7e
 
 
15e5321
 
f28e10e
 
 
 
 
771433c
f28e10e
 
 
 
15e5321
 
f28e10e
15e5321
 
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
58
59
60
61
62
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'))
    )