You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. from flask import ( Flask, render_template, request, abort, redirect,
  2. send_from_directory, url_for, session, flash, get_flashed_messages)
  3. from flask_session import Session
  4. import openai
  5. from dotenv import load_dotenv
  6. from markdown import markdown
  7. import requests
  8. from glob import glob
  9. import json
  10. import os
  11. import sys
  12. import time
  13. import shutil
  14. import re
  15. import secrets
  16. RE_VID = re.compile("""\[video ["']([^['"]*?)["']\]""")
  17. TEMPLATE_VID = """<video controls class="centered"><source src="{}" type="video/{}"></video>"""
  18. def preprocess_content(defs):
  19. md = defs.get("markdown", "")
  20. if md:
  21. content = markdown(md)
  22. content = RE_VID.sub(lambda m: TEMPLATE_VID.format(m.group(1), m.group(1).split('.')[-1]), content)
  23. else:
  24. content = ""
  25. img = defs.get("image", {})
  26. match img.get("placement", "none"):
  27. case "above":
  28. content = """<img src="{source}" alt="{alt}" class="centered w-{width}"/><br/>\n""".format(**img)+content
  29. case "left":
  30. content = """<img src="{source}" alt="{alt}" class="float-left w-{width}"/><br/>\n""".format(**img)+content
  31. case "right":
  32. content = """<img src="{source}" alt="{alt}" class="float-right w-{width}"/><br/>\n""".format(**img)+content
  33. case "below":
  34. content = content+"""<br/>\n<img src="{source}" alt="{alt}" class="centered w-{width}"/><br/>\n""".format(**img)
  35. if defs.get("use_soundtrack"):
  36. content = """<audio loop data-autoplay><source src="{}" type="audio/{}"></audio>\n""".format(
  37. defs["soundtrack"], defs["soundtrack"].split(".")[-1])+content
  38. return content
  39. def preprocess_payload(payload):
  40. for column in payload.get("columns", []):
  41. column["content"] = preprocess_content(column)
  42. for slide in column.get("slides", []):
  43. slide["content"] = preprocess_content(slide)
  44. RE_YOUTUBE = re.compile("https://(?:www.)?youtube.com/watch\?v=(?P<code>[^/?]*)")
  45. RE_YOUTU_BE = re.compile("https://(?:www.)?youtu.be/(?P<code>[^/?]*)")
  46. RE_VIMEO = re.compile("https://(?:www.)?vimeo.com/(?P<code>[^/?]*)")
  47. def preprocess_embed(e):
  48. res = {}
  49. url = e.get("url")
  50. if not url:
  51. return None
  52. for key in ["id", "description", "proportions"]:
  53. val = e.get(key)
  54. if not val:
  55. return None
  56. res[key] = val
  57. m = RE_YOUTUBE.search(url) or RE_YOUTU_BE.search(url)
  58. if m:
  59. res["type"] = "youtube"
  60. res["code"] = m.group("code")
  61. else:
  62. m = RE_VIMEO.search(url)
  63. if m:
  64. res["type"] = "vimeo"
  65. res["code"] = m.group("code")
  66. else:
  67. return None
  68. return res
  69. def get_all_embeds():
  70. embeds = json.load(open("static/media/video-embed.json"))
  71. embeds = [preprocess_embed(e) for e in embeds]
  72. embeds = [e for e in embeds if e]
  73. return embeds
  74. def deref_schema(val):
  75. "Deref all `$ref` entries in a json-schema"
  76. if type(val)==type([]):
  77. return [deref_schema(item) for item in val]
  78. elif type(val)==type({}):
  79. val = dict(val)
  80. if "$ref" in val:
  81. ref = val["$ref"]
  82. if ref.startswith("#"):
  83. pass # stub. Currently we don't have internal references...
  84. elif ref.startswith("/"):
  85. ref = url_for("home", _external=True)+ref[1:]
  86. val.update(requests.get(ref).json())
  87. del val["$ref"]
  88. for key in val:
  89. val[key] = deref_schema(val[key])
  90. return val
  91. else:
  92. return val
  93. def file2json(path):
  94. "returns json string without line breaks and indent"
  95. return json.dumps(json.load(open(path)))
  96. def make_prompt(username):
  97. user = open("static/users/{}.txt".format(username)).read()
  98. json_schema = json.dumps(schema())
  99. json_example = file2json("static/chat-example.json")
  100. img_enum = json.dumps(choices("img"))
  101. return render_template("prompt.txt", user=user, schema=json_schema, example=json_example, img_enum=img_enum)
  102. load_dotenv()
  103. openai.organization = "org-GFWgNyt7NSKpCv6GhzXYZTpi"
  104. application = Flask(__name__)
  105. application.config["SECRET_KEY"] = secrets.token_hex()
  106. application.config["SESSION_TYPE"] = 'filesystem'
  107. Session(application)
  108. @application.route("/", methods=['GET', 'POST'])
  109. def home():
  110. is_initial = False
  111. if "messages" not in session:
  112. if "user" not in session:
  113. session["user"] = "odelia" # terrible kludge
  114. session["messages"] = [
  115. {"role": "system", "content": make_prompt(session["user"])},
  116. {"role": "assistant", "content": file2json("static/initial-chat.json")}
  117. ]
  118. session["history"] = []
  119. is_initial = True
  120. prompt = ""
  121. if request.method=='POST' or is_initial:
  122. if is_initial:
  123. session["messages"] += [{"role": "system", "content": "User wishes to begin. Remember to find out how they feel before offering a ceremony or other action."}]
  124. else:
  125. prompt = request.form["prompt"].strip()
  126. if prompt:
  127. session["messages"] += [{"role": "user", "content": prompt}]
  128. else:
  129. session["messages"] += [{"role": "system", "content": "User has hit enter. Please continue."}]
  130. payload = None
  131. while not payload:
  132. reply = openai.ChatCompletion.create(model=os.environ["MODEL_NAME"], messages=session["messages"])
  133. message = dict(reply["choices"][0]["message"])
  134. session["messages"] += [message]
  135. try:
  136. payload = json.loads(message["content"])
  137. payload["prompt"] = prompt.replace('"', '\"')
  138. payload["content"] = preprocess_content(payload)
  139. if payload.get("use_video_content"):
  140. embed_id = payload.get("video_content")
  141. if embed_id:
  142. embeds = get_all_embeds()
  143. embeds = [e for e in embeds if e["id"]==embed_id]
  144. if embeds:
  145. payload["embed"] = embeds[0]
  146. session["history"] += [dict(payload)] # shallow copy so history doesn't get added later on
  147. except Exception as e:
  148. print(repr(e))
  149. session["messages"] += [{"role": "system", "content": "reply was ignored because it's not valid JSON. User is unaware. Do NOT apologize to them. Simply rephrase your previous answer as valid JSON that complies with the schema in the initial system prompt of this chat. It is followed by an example you can learn from."}]
  150. print("=====")
  151. print(reply["choices"][0]["message"]["content"])
  152. print("-----")
  153. print(payload)
  154. print("=====")
  155. else:
  156. payload = json.loads(session["messages"][-1]["content"])
  157. payload["content"] = preprocess_content(payload)
  158. payload["history"] = list(reversed(session["history"][:-1]))
  159. return render_template("chat.html", **payload)
  160. @application.get("/reset/<string:user>")
  161. def reset(user):
  162. if not os.path.isfile("static/users/{}.txt".format(user)):
  163. flash("user {} not found".format(user), 'error')
  164. return redirect(url_for('home'))
  165. for key in ["messages", "history"]:
  166. if key in session:
  167. del session[key]
  168. session["user"] = user
  169. return redirect(url_for('home'))
  170. @application.get("/schema.json")
  171. def schema():
  172. "return deref_schema of `chat.schema.json` file's content"
  173. return deref_schema(json.load(open("static/chat.schema.json")))
  174. @application.get("/slides")
  175. def slides():
  176. "Legacy multi-slide format"
  177. payload = json.load(open("static/slides.json"))
  178. preprocess_payload(payload)
  179. return render_template("slides.html", generate_indices=False, **payload)
  180. @application.get("/example")
  181. def example():
  182. payload = json.load(open("static/chat-example.json"))
  183. payload["content"] = preprocess_content(payload)
  184. if payload.get("use_video_content"):
  185. embed_id = payload.get("video_content")
  186. if embed_id:
  187. embeds = get_all_embeds()
  188. embeds = [e for e in embeds if e["id"]==embed_id]
  189. if embeds:
  190. payload["embed"] = embeds[0]
  191. return render_template("example.html", **payload)
  192. @application.get("/embeds")
  193. def embeds():
  194. embeds = get_all_embeds()
  195. return render_template("embeds.html", embeds=embeds)
  196. @application.post("/update")
  197. def update():
  198. "Legacy multi-slide format"
  199. shutil.copy(
  200. "static/slides.json",
  201. time.strftime(
  202. "editor-archive/slides-%Y-%m-%d-%H.%M.%S.json",
  203. time.localtime()))
  204. payload = request.get_json()
  205. print(type(payload))
  206. json.dump(payload, sys.stdout, indent=4)
  207. json.dump(payload, open("static/slides.json", "w"), indent=4)
  208. return {"status": "success"}
  209. @application.post("/update-embeds")
  210. def update_embeds():
  211. shutil.copy(
  212. "static/media/video-embed.json",
  213. time.strftime(
  214. "editor-archive/embeds-%Y-%m-%d-%H.%M.%S.json",
  215. time.localtime()))
  216. payload = request.get_json()
  217. print(type(payload))
  218. json.dump(payload, sys.stdout, indent=4)
  219. json.dump(payload, open("static/media/video-embed.json", "w"), indent=4)
  220. return {"status": "success"}
  221. @application.post("/update-chat")
  222. def update_chat():
  223. shutil.copy(
  224. "static/chat-example.json",
  225. time.strftime(
  226. "editor-archive/chat-%Y-%m-%d-%H.%M.%S.json",
  227. time.localtime()))
  228. payload = request.get_json()
  229. print(type(payload))
  230. json.dump(payload, sys.stdout, indent=4)
  231. json.dump(payload, open("static/chat-example.json", "w"), indent=4)
  232. return {"status": "success"}
  233. @application.get("/enum/<topic>")
  234. def choices(topic):
  235. if topic in ["img", "bg", "bg-video", "audio"]:
  236. choices = glob("static/media/{}/*.*".format(topic))
  237. titles = [os.path.basename(c) for c in choices]
  238. try:
  239. descdir = json.load(open("static/media/{}.json".format(topic)))
  240. except FileNotFoundError:
  241. descdir = {}
  242. return {
  243. "type": "string",
  244. "enum": choices,
  245. "options": {
  246. "enum_titles": [descdir.get(t, t.rsplit(".", 1)[0]) for t in titles]
  247. }
  248. }
  249. abort(404)
  250. @application.get("/embeds_enum")
  251. def embeds_enum():
  252. embeds = get_all_embeds()
  253. return {
  254. "enum": [e["id"] for e in embeds],
  255. "options": { "enum_titles": [e["description"] for e in embeds] }
  256. }
  257. @application.route("/save", methods=['GET', 'POST'])
  258. def save():
  259. if request.method=="POST":
  260. filename = request.form["filename"].rsplit("/",1)[-1]
  261. if filename:
  262. path = "archive/{}.json".format(filename)
  263. is_overwrite = os.path.isfile(path)
  264. moment = {
  265. key: session.get(key, [])
  266. for key in ["messages", "history"]
  267. }
  268. print(moment)
  269. json.dump(moment, open(path,"w"), indent=4)
  270. if is_overwrite:
  271. flash("Successfully overwritten {}.json".format(filename))
  272. else:
  273. flash("Successfully saved to {}.json".format(filename))
  274. else:
  275. flash("Invalid filename. Save aborted.", "error")
  276. return redirect(url_for("home"))
  277. else:
  278. return render_template("save.html",
  279. suggestion=time.strftime(
  280. "moment-%Y-%m-%d-%H.%M.%S"),
  281. files = [os.path.basename(path).rsplit(".",1)[0] for path in glob("archive/*.json")])
  282. @application.route("/load", methods=['GET', 'POST'])
  283. def load():
  284. if request.method=="POST":
  285. filename = request.form["filename"]
  286. try:
  287. moment = json.load(open("archive/{}.json".format(filename)))
  288. session["messages"] = moment["messages"]
  289. session["history"] = moment["history"]
  290. except Exception as e:
  291. flash(repr(e))
  292. return redirect(url_for("home")+"#/oldest")
  293. else:
  294. return render_template("load.html",
  295. files = [os.path.basename(path).rsplit(".",1)[0] for path in glob("archive/*.json")])
  296. @application.get("/embed-editor")
  297. def embed_editor():
  298. return render_template("embed-editor.html")
  299. @application.get("/chat-editor")
  300. def chat_editor():
  301. return render_template("chat-editor.html")
  302. @application.get("/editor")
  303. def editor():
  304. "Legacy multi-slide format"
  305. return render_template("editor.html")
  306. @application.route("/img", methods=['GET', 'POST'])
  307. def image():
  308. if request.method=='GET':
  309. src = "static/img/marble-question-mark.png"
  310. alt = "A question mark"
  311. prompt = ""
  312. else:
  313. prompt = request.form["prompt"]
  314. alt = prompt
  315. response = openai.Image.create(prompt=prompt, n=1, size="1024x1024")
  316. src = response['data'][0]['url']
  317. return render_template("image.html", src=src, alt=alt, prompt=prompt)
  318. @application.route("/favicon.ico")
  319. def favicon():
  320. return send_from_directory(os.path.join(application.root_path, "static"),
  321. "favicon.ico", mimetype="image/vnd.microsoft.icon")