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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. from flask import ( Flask, render_template, request, abort, redirect,
  2. send_from_directory, url_for, session)
  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. def deref_schema(val):
  45. "Deref all `$ref` entries in a json-schema"
  46. if type(val)==type([]):
  47. return [deref_schema(item) for item in val]
  48. elif type(val)==type({}):
  49. val = dict(val)
  50. if "$ref" in val:
  51. ref = val["$ref"]
  52. if ref.startswith("#"):
  53. pass # stub. Currently we don't have internal references...
  54. elif ref.startswith("/"):
  55. ref = url_for("home", _external=True)+ref[1:]
  56. val.update(requests.get(ref).json())
  57. del val["$ref"]
  58. for key in val:
  59. val[key] = deref_schema(val[key])
  60. return val
  61. else:
  62. return val
  63. def file2json(path):
  64. "returns json string without line breaks and indent"
  65. return json.dumps(json.load(open(path)))
  66. def make_prompt():
  67. json_schema = json.dumps(schema())
  68. json_example = file2json("static/chat-example.json")
  69. return render_template("prompt.txt", schema=json_schema, example=json_example)
  70. load_dotenv()
  71. openai.organization = "org-GFWgNyt7NSKpCv6GhzXYZTpi"
  72. application = Flask(__name__)
  73. application.config["SECRET_KEY"] = secrets.token_hex()
  74. application.config["SESSION_TYPE"] = 'filesystem'
  75. Session(application)
  76. @application.route("/", methods=['GET', 'POST'])
  77. def home():
  78. if "messages" not in session:
  79. session["messages"] = [
  80. {"role": "system", "content": make_prompt()},
  81. {"role": "assistant", "content": file2json("static/initial-chat.json")}
  82. ]
  83. if "history" not in session:
  84. session["history"] = []
  85. if request.method=='POST':
  86. prompt = request.form["prompt"].strip()
  87. if prompt:
  88. session["messages"] += [{"role": "user", "content": prompt}]
  89. else:
  90. session["messages"] += [{"role": "system", "content": "User has hit enter. Please continue."}]
  91. payload = None
  92. while not payload:
  93. reply = openai.ChatCompletion.create(model=os.environ["MODEL_NAME"], messages=session["messages"])
  94. session["messages"] += [reply["choices"][0]["message"]]
  95. try:
  96. payload = json.loads(reply["choices"][0]["message"]["content"])
  97. payload["prompt"] = prompt.replace('"', '\"')
  98. payload["content"] = preprocess_content(payload)
  99. session["history"].append(payload)
  100. except Exception as e:
  101. print(repr(e))
  102. session["messages"] += [{"role": "system", "content": "reply was ignored because it's not a valid json. user is unaware. do not apologize to them"}]
  103. print("=====")
  104. print(reply["choices"][0]["message"]["content"])
  105. print("-----")
  106. print(payload)
  107. print("=====")
  108. else:
  109. payload = json.loads(session["messages"][-1]["content"])
  110. payload["content"] = preprocess_content(payload)
  111. payload["history"] = reversed(session["history"][:-1])
  112. return render_template("chat.html", **payload)
  113. @application.get("/reset")
  114. def reset():
  115. for key in ["messages", "history"]:
  116. if key in session:
  117. del session[key]
  118. return redirect(url_for('home'))
  119. @application.get("/schema.json")
  120. def schema():
  121. "return deref_schema of `chat.schema.json` file's content"
  122. return deref_schema(json.load(open("static/chat.schema.json")))
  123. @application.get("/messages.json")
  124. def dump_messages():
  125. if "messages" not in session:
  126. session["messages"] = [
  127. {"role": "system", "content": make_prompt()},
  128. {"role": "assistant", "content": file2json("static/initial-chat.json")}
  129. ]
  130. return session["messages"]
  131. @application.get("/slides")
  132. def slides():
  133. "Legacy multy-slide format"
  134. payload = json.load(open("static/slides.json"))
  135. preprocess_payload(payload)
  136. return render_template("slides.html", generate_indices=False, **payload)
  137. @application.post("/update")
  138. def update():
  139. "Legacy multy-slide format"
  140. shutil.copy(
  141. "static/slides.json",
  142. time.strftime(
  143. "archive/slides-%Y-%m-%d-%H.%M.%S.json",
  144. time.localtime()))
  145. payload = request.get_json()
  146. print(type(payload))
  147. json.dump(payload, sys.stdout, indent=4)
  148. json.dump(payload, open("static/slides.json", "w"), indent=4)
  149. return {"status": "success"}
  150. @application.post("/update-chat")
  151. def update_chat():
  152. shutil.copy(
  153. "static/chat.json",
  154. time.strftime(
  155. "archive/chat-%Y-%m-%d-%H.%M.%S.json",
  156. time.localtime()))
  157. payload = request.get_json()
  158. print(type(payload))
  159. json.dump(payload, sys.stdout, indent=4)
  160. json.dump(payload, open("static/chat.json", "w"), indent=4)
  161. return {"status": "success"}
  162. @application.get("/enum/<topic>")
  163. def choices(topic):
  164. if topic in ["img", "bg", "bg-video", "audio"]:
  165. choices = glob("static/media/{}/*.*".format(topic))
  166. titles = [os.path.basename(c) for c in choices]
  167. try:
  168. descdir = json.load(open("static/media/{}.json".format(topic)))
  169. except FileNotFoundError:
  170. descdir = {}
  171. return {
  172. "type": "string",
  173. "enum": choices,
  174. "options": {
  175. "enum_titles": [descdir.get(t, t.rsplit(".", 1)[0]) for t in titles]
  176. }
  177. }
  178. abort(404)
  179. @application.get("/chat-editor")
  180. def chat_editor():
  181. return render_template("chat-editor.html")
  182. @application.get("/editor")
  183. def editor():
  184. "Legacy multy-slide format"
  185. return render_template("editor.html")
  186. @application.route("/img", methods=['GET', 'POST'])
  187. def image():
  188. if request.method=='GET':
  189. src = "static/img/marble-question-mark.png"
  190. alt = "A question mark"
  191. prompt = ""
  192. else:
  193. prompt = request.form["prompt"]
  194. alt = prompt
  195. response = openai.Image.create(prompt=prompt, n=1, size="1024x1024")
  196. src = response['data'][0]['url']
  197. return render_template("image.html", src=src, alt=alt, prompt=prompt)
  198. @application.route("/favicon.ico")
  199. def favicon():
  200. return send_from_directory(os.path.join(application.root_path, "static"),
  201. "favicon.ico", mimetype="image/vnd.microsoft.icon")