ashawkey commited on
Commit
e1e482a
1 Parent(s): 1ee83d1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import os
4
+ import openai
5
+
6
+ INIT_PROMPT = """
7
+ I would like to engage your services as an academic writing consultant to improve my writing.
8
+ I will provide you with text that requires refinement, and you will enhance it with more academic language and sentence structures.
9
+ The essence of the text should remain unaltered, including any LaTeX commands.
10
+ I request that you provide only the improved version of the text without any further explanations.
11
+ """
12
+
13
+ PREFIX_PROMPT = "Please refine the following text in academic English: \n"
14
+
15
+ print(f'[INFO] Loading API key from env...')
16
+
17
+ openai.api_key = os.getenv("OPENAI_API_KEY")
18
+
19
+ if openai.api_key is None:
20
+ print('[WARN] OPENAI_API_KEY key not found in env')
21
+
22
+ def submit(x, simple=False):
23
+ # everytime we restart a new conversation.
24
+ if simple:
25
+ results = openai.ChatCompletion.create(
26
+ model="gpt-3.5-turbo",
27
+ messages=[
28
+ {"role": "user", "content": PREFIX_PROMPT + x},
29
+ ]
30
+ )
31
+ else:
32
+ results = openai.ChatCompletion.create(
33
+ model="gpt-3.5-turbo",
34
+ messages=[
35
+ {"role": "system", "content": INIT_PROMPT},
36
+ {"role": "user", "content": PREFIX_PROMPT + x},
37
+ ]
38
+ )
39
+ total_tokens = results['usage']['total_tokens']
40
+ cost = (total_tokens / 1000) * 0.002 # in dollar
41
+ response = results['choices'][0]['message']['content']
42
+ return response, cost
43
+
44
+ print(f'[INFO] Starting Gradio APP...')
45
+
46
+ with gr.Blocks() as app:
47
+ gr.Markdown("### ChatGPT, please help to improve my paper writing!")
48
+
49
+ # allow setting API key in gui
50
+ with gr.Row():
51
+ api_input = gr.Textbox(label="OPENAI_API_KEY", value=openai.api_key, lines=1)
52
+ def save_api(x): openai.api_key = x
53
+ api_input.change(save_api, api_input)
54
+
55
+ simple_checkbox = gr.Checkbox(value=False, label='simple mode (only send the prefix prompt, 0.00142$ cheaper per query)')
56
+
57
+ with gr.Row():
58
+
59
+ text_input = gr.Textbox(label="Input", lines=10)
60
+
61
+ with gr.Column():
62
+ text_output = gr.Textbox(label="Output", lines=10)
63
+ cost = gr.Number(label='cost of this query ($)')
64
+
65
+ text_button = gr.Button("Submit")
66
+ text_button.click(submit, inputs=[text_input, simple_checkbox], outputs=[text_output, cost])
67
+
68
+ app.launch()