9 Sample Project
Notebook 9 - Sample Project¶
Make a copy of this notebook by selecting File->Save a copy in Drive from the menu bar above.
Things you'll learn in this lesson:
- example code and philosophy from a real Python project
Introducing Quizaic¶
Application Architecture¶
Web Server¶
https://github.com/mco-gh/quizaic/blob/main/api/main.py
from flask import Response, Flask, g, request
resource = [
“admins”,
“quizzes”,
“results”,
“sessions”,
“generators”,
]
app = Flask(name)
@app.route(”/<resource_name>", methods=[“GET”])
def handle_list(resource_name):
if resource_name not in resource:
return “Not found”, 404
return methods.list(resource_name)
Get a Resource¶
https://github.com/mco-gh/quizaic/blob/main/api/resources/methods.py
def get(resource_kind, id):
log(f"Request to get {resource_kind}", severity="INFO")
if resource_kind not in resource_fields:
return "Not found", 404, {}
if resource_kind == "sessions" and id == "me":
id = get_hashed_email()
result = db.fetch(resource_kind, id, resource_fields[resource_kind])
if result is None:
return "Not found", 404, {}
return (
json.dumps(result),
200,
{"Content-Type": "application/json", "ETag": base.etag(result)},
)
Access Checking¶
https://github.com/mco-gh/quizaic/blob/main/api/resources/auth.py
def user_logged_in(email):
return email != None
def user_created_quiz(hashed_email, quiz_id):
if hashed_email is None:
return False
quiz = db.fetch(“quizzes”, quiz_id, [“creator”])
if quiz and quiz[“creator”] == hashed_email:
return True
return False
Generate a Quiz¶
https://github.com/mco-gh/quizaic/blob/main/api/pyquizaic/generators/quiz/gemini-pro/quizgen.py
def gen_quiz(
self,
topic=BaseQuizgen.TOPIC,
num_questions=BaseQuizgen.NUM_QUESTIONS,
num_answers=BaseQuizgen.NUM_ANSWERS,
difficulty=BaseQuizgen.DIFFICULTY,
language=BaseQuizgen.LANGUAGE,
temperature=BaseQuizgen.TEMPERATURE,
):
# print(f"{topic=}, {num_questions=}, {num_answers=}, {difficulty=}, {language=}")
file_path = os.path.join(os.path.dirname(__file__), f"../prompt.txt")
with open(file_path, encoding="utf-8") as fp:
self.prompt_template = fp.read()
prompt = self.prompt_template.format(
topic=topic,
num_questions=num_questions,
num_answers=num_answers,
language=language,
difficulty=difficulty,
)
prediction = self.predict_llm(
MODEL, prompt, temperature, MAX_OUTPUT_TOKENS, TOP_P, TOP_K
)
prediction = prediction.strip()
prediction = re.sub('.*``` *(json)?', '', prediction)
prediction = prediction[prediction.find('['):]
parsed = ""
level = 0
for i in prediction:
if i == "[":
level += 1
elif i == "]":
level -= 1
parsed += i
if level <= 0:
break
prediction = parsed
print("prediction=", prediction)
quiz = json.loads(prediction)
#print(f"{quiz=}")
# Make sure the correct answer appears randomly in responses
for i in quiz:
random.shuffle(i["responses"])
return quiz