Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import openai
|
| 2 |
+
import os
|
| 3 |
+
import gradio as gr
|
| 4 |
+
|
| 5 |
+
from dotenv import load_dotenv, find_dotenv
|
| 6 |
+
_ = load_dotenv(find_dotenv())
|
| 7 |
+
|
| 8 |
+
openai.api_key = os.environ.get("OPENAI_API_KEY")
|
| 9 |
+
openai.api_base="https://api.fe8.cn/v1"
|
| 10 |
+
|
| 11 |
+
class Conversation:
|
| 12 |
+
def __init__(self, num_of_round):
|
| 13 |
+
self.num_of_round = num_of_round
|
| 14 |
+
self.messages = []
|
| 15 |
+
|
| 16 |
+
def ask(self, text_to_rewrite, question):
|
| 17 |
+
try:
|
| 18 |
+
self.messages.append({"role": "user", "content": question})
|
| 19 |
+
response = openai.Completion.create(
|
| 20 |
+
model="text-davinci-003",
|
| 21 |
+
prompt=f"{text_to_rewrite}",
|
| 22 |
+
max_tokens=1024,
|
| 23 |
+
)
|
| 24 |
+
rewritten_text = response.choices[0].text
|
| 25 |
+
self.messages.append({"role": "assistant", "content": rewritten_text})
|
| 26 |
+
except Exception as e:
|
| 27 |
+
print(e)
|
| 28 |
+
return e
|
| 29 |
+
|
| 30 |
+
if len(self.messages) > self.num_of_round * 2:
|
| 31 |
+
self.messages.pop(0)
|
| 32 |
+
self.messages.pop(0)
|
| 33 |
+
|
| 34 |
+
return rewritten_text, self.messages
|
| 35 |
+
|
| 36 |
+
conv = Conversation(10)
|
| 37 |
+
|
| 38 |
+
def answer(question, text_to_rewrite, history=[]):
|
| 39 |
+
rewritten_text, messages = conv.ask(text_to_rewrite, question)
|
| 40 |
+
history.append(question)
|
| 41 |
+
history.append(text_to_rewrite)
|
| 42 |
+
history.append(rewritten_text)
|
| 43 |
+
return rewritten_text, history
|
| 44 |
+
|
| 45 |
+
with gr.Blocks(css="#chatbot{height:300px} .overflow-y-auto{height:500px}") as demo:
|
| 46 |
+
chatbot = gr.Chatbot(elem_id="chatbot")
|
| 47 |
+
state = gr.State([])
|
| 48 |
+
|
| 49 |
+
with gr.Row():
|
| 50 |
+
txt = gr.Textbox(label="输入要改写的文本").style(container=False)
|
| 51 |
+
question = gr.Textbox(label="输入对话问题").style(container=False)
|
| 52 |
+
|
| 53 |
+
txt.submit(answer, [question, txt, state], [chatbot, state])
|
| 54 |
+
|
| 55 |
+
demo.launch()
|