from fasthtml_hf import setup_hf_backup
import pandas as pd
import random
import json
import traceback
from fasthtml.common import *
# Initialize the fastHtml application
app, rt = fast_app()
basepath = "/Users/manaranjanp/Documents/Work/MyLearnings/fastHTML/ClassApp"
topics = ['Science', 'Social']
chapters = {
'Science': ['Separation_of_Substances',
'Components_of_Food',
'Getting_to_Know_Plants',
'Motion_and_Measurements',
'Lights_and_Reflections'],
'Social': ['History', 'Civics']
}
class QuestionLoader:
def __init__(self, json_file):
# Load the Excel file and store each sheet as a dictionary of dictionaries
self.data = self.load_json_file(json_file)
def load_json_file(self, file_path):
with open(file_path, 'r') as file:
json_data = json.load(file) # Load the JSON data as a Python dictionary
return json_data
def random_question(self):
# Select a random sheet
random_sheet = random.choice(list(self.data.keys()))
# Select a random question from the sheet
random_question = random.choice(self.data[random_sheet])
print(f"Sheet {random_sheet}")
print(f"Question: {random_question}")
return random_sheet, random_question
# default_file_path = os.path.join(basepath, "Science_Separation_of_Substances.json")
def load_questions(qpath):
return QuestionLoader(qpath)
# q_loader = load_questions(default_file_path)
def mk_opts(nm, cs):
return (
Option(f'-- select {nm} --', disabled='', selected='', value=''),
*map(Option, cs))
@app.get('/getchapters')
def getchapters(topic: str):
print(topic)
return Div(Select(*mk_opts('chapter', chapters[topic]), name='chapter'))
# Define the route for the homepage
@app.get('/')
def homepage():
return Titled('Grade 6: Study Companion', Grid( getConfigForm(),
Div(
Div(id="result", style ="font-family:Helvetica; font-size=24pt;")
)
, style="grid-template-columns: 400px 1000px; gap: 50px;"
), style="color:#DC143C; font-size:25px;")
# Function to generate the configuration form for the web interface
def getConfigForm():
topics_dropdown = Select(
*mk_opts('topic', topics),
name='topic',
get='getchapters', hx_target='#chapters')
return Card(Form(hx_post="/submit", hx_target="#result", hx_swap_oob="innerHTML")(
Div(
Label("Topics:", for_="topics"),
topics_dropdown),
Div(
Label("Chapters:", for_="chapter"),
# Div(Div(id='chapters'))),
Div(Select(*mk_opts('chapter', chapters["Science"]), name='chapter'), id='chapters')),
Div(
Button("Load Questions")
),
Div(
Br(),
A("Developed by Manaranjan Pradhan", href="http://www.manaranjanp.com/",
target="_blank",
style = 'color: red; font-size: 16px;')
)))
def format_questions(sheet, question_data):
if(sheet == "MCQ"):
return Div(Label(Strong(sheet) , style="color:#F4A460; font-size:40px;"),
Label(Strong(question_data['question']), style="color:#3498db; font-size:25px;"),
Label("A. " + question_data['option_a']),
Label("B. " + question_data['option_b']),
Label("C. " + question_data['option_c']),
Label("D. " + question_data['option_d']),
Div(Div(id='qanswer'), Form(hx_post="/getanswer", hx_target="#qanswer")(
Hidden(question_data['answer'], id = 'answer'),
Button("Show Answer")), id='qanswer'))
else:
return Div(Label(Strong(sheet) , style="color:#F4A460; font-size:40px;"),
Label(Strong(question_data['question']), style="color:#3498db; font-size:25px;"),
Div(Div(id='qanswer'), Form(hx_post="/getanswer", hx_target="#qanswer")(
Hidden(question_data['answer'], id = 'answer'),
Button("Show Answer")), id='qanswer'))
# Define the route for form submission
@app.post('/submit')
async def post(d:dict):
try:
# Check if a file was uploaded
# file_path = os.path.join(basepath, d['topic'] + "_" + d['chapter'] + ".json")
q_loader = load_questions(d['topic'] + "_" + d['chapter'] + ".json")
sheet_name, question_data = q_loader.random_question()
return Card(
Div(format_questions(sheet_name, question_data)),
P(),
Div(Form(hx_post="/submit", hx_target="#result")(
Hidden(d['topic'], id = 'topic'),
Hidden(d['chapter'], id = 'chapter'),
Button("Next Question"))))
return
except BaseException as e:
print(traceback.format_exc())
return str(e)
# Define the route for form submission
@app.post('/getanswer')
async def getanswer(d:dict):
try:
print(f"Answer: {d['answer']}")
return Div(
P(Label(Strong("Answer"), style="color:#F4A460; font-size:40px;")),
Label(Strong(d['answer']), style="color:#FF4500; font-size:25px;"))
except BaseException as e:
print(traceback.format_exc())
return str(e)
setup_hf_backup(app)
# Start the FastAPI server
serve()