ananya1011 commited on
Commit
28b8a63
·
1 Parent(s): 588d356
Files changed (1) hide show
  1. app.py +120 -0
app.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import json
3
+ from flask import Flask, request, jsonify
4
+ from flask_cors import CORS, cross_origin
5
+
6
+ app = Flask(__name__)
7
+ cors = CORS(app)
8
+ app.config['CORS_HEADERS'] = 'Content-Type'
9
+ openai.api_key = ""
10
+
11
+ db = {}
12
+
13
+ @app.route("/get-continue-story", methods=["GET"])
14
+ def get_continue_story():
15
+ args = request.args
16
+
17
+ if args['id'] not in db.keys() and not len(args['decision']):
18
+ db[args['id']] = [
19
+ {"role": "system", "content": f"""You're a story writer. The mood of the story: {args['mood']}.
20
+ The main character: {args['mainCharacter']}.
21
+ Setting of the story: {args['settingStory']}."""}]
22
+
23
+ if args['id'] not in db.keys() and len(args['decision']):
24
+ db[args['id']] = [
25
+ {"role": "system", "content": f"""You're a story writer.
26
+ The beginning of the story is as follows: {args['decision']}"""}]
27
+ args['decision'] = ""
28
+
29
+ if len(args['decision']):
30
+ db[args['id']].append({"role": "assistant", "content": args['decision']})
31
+
32
+ db[args['id']].append({"role": "user", "content": args['storyPoint']})
33
+
34
+ try:
35
+ completion = openai.ChatCompletion.create(
36
+ model="gpt-3.5-turbo",
37
+ messages=db[args['id']],
38
+ temperature=0.8,
39
+ max_tokens=340
40
+ )
41
+
42
+ db[args['id']].append(completion.choices[0].message)
43
+ except Exception as e:
44
+ print(e)
45
+ return jsonify({ "ok": False, "error": str(e)}), 500
46
+
47
+ resp = args['decision'] + completion.choices[0].message.content
48
+
49
+ if resp[-1] != '.':
50
+ resp = crop_text(resp)
51
+
52
+
53
+ if 'happy ending' in args['storyPoint']:
54
+ with open('./bd.txt', 'a') as fl:
55
+ story = '\n'.join([i['content'] for i in db[args['id']]])
56
+ fl.write(f"""{args['id']}
57
+ {story}""" + "\n")
58
+
59
+ return jsonify({ "ok": True, "new_part": resp })
60
+
61
+
62
+ @app.route("/decisions", methods=["GET"])
63
+ def get_story_decisions():
64
+ args = request.args
65
+
66
+ while True:
67
+ completion = openai.ChatCompletion.create(
68
+ model="gpt-3.5-turbo",
69
+ messages=get_decision(db[args['id']]),
70
+ temperature=0.5,
71
+ max_tokens=340
72
+ )
73
+
74
+ resp = completion.choices[0].message.content
75
+ print(resp)
76
+
77
+ try:
78
+ res = response_processing(resp)
79
+ if len(res.keys()) != 3:
80
+ continue
81
+ except Exception as e:
82
+ print(e)
83
+ continue
84
+ else:
85
+ break
86
+
87
+ return jsonify({ "ok": True, "data": res })
88
+
89
+ def response_processing(resp):
90
+ result = {}
91
+ mas = [i for i in resp.split('{')][1:]
92
+ mas = [i.split('}') for i in mas]
93
+ mas = [i[0].replace('\n', '') for i in mas]
94
+
95
+ for m in mas:
96
+ c = m.split(':')
97
+ c = [i.split('"') for i in c]
98
+ result[c[0][1]] = c[1][1]
99
+
100
+ return json.loads(json.dumps(result))
101
+
102
+ def get_decision(db):
103
+ return db + [{
104
+ "role": "user", "content": """Come up with three short different story continuations.
105
+ Write them to me in json format, where the key is the name of the continuation, and the value is the text.
106
+ Output example:
107
+ {
108
+ 'name_story': 'value',
109
+ 'name_story': 'value',
110
+ 'name_story': 'value'
111
+ }"""
112
+ }]
113
+
114
+ def crop_text(text):
115
+ text_arr = text.split(".")
116
+ res = ".".join(text_arr[:-1])
117
+ return f'{res}.'
118
+
119
+ if __name__ == '__main__':
120
+ app.run(debug=True,port=5623)