Added the ability to generate Listening exams as well

This commit is contained in:
Tiago Ribeiro
2023-11-29 17:19:47 +00:00
parent c90234cefc
commit 1f0e5f4a08
6 changed files with 171 additions and 25 deletions

View File

@@ -1,9 +1,13 @@
import Input from "@/components/Low/Input";
import {ListeningPart} from "@/interfaces/exam";
import {Exercise, ListeningExam} from "@/interfaces/exam";
import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams";
import {checkSound} from "@/utils/sound";
import {convertCamelCaseToReadable} from "@/utils/string";
import {Tab} from "@headlessui/react";
import axios from "axios";
import clsx from "clsx";
import {useRouter} from "next/router";
import {useState} from "react";
import {BsArrowRepeat} from "react-icons/bs";
import {toast} from "react-toastify";
@@ -20,8 +24,11 @@ const PartTab = ({part, types, index, setPart}: {part?: ListeningPart; types: st
setPart(undefined);
setIsLoading(true);
axios
.get(`/api/exam/listening/generate/listening_passage_${index}${topic || types ? `?${url.toString()}` : ""}`)
.then((result) => setPart(result.data))
.get(`/api/exam/listening/generate/listening_section_${index}${topic || types ? `?${url.toString()}` : ""}`)
.then((result) => {
checkSound();
setPart(result.data);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
@@ -67,16 +74,44 @@ const PartTab = ({part, types, index, setPart}: {part?: ListeningPart; types: st
</span>
))}
</div>
{typeof part.text === "string" && <span className="w-full h-96">{part.text.replaceAll("\n\n", " ")}</span>}
{typeof part.text !== "string" && (
<div className="w-full h-96 flex flex-col gap-2">
{part.text.conversation.map((x, index) => (
<span key={index} className="flex gap-1">
<span className="font-semibold">{x.name}:</span>
{x.text.replaceAll("\n\n", " ")}
</span>
))}
</div>
)}
</div>
)}
</Tab.Panel>
);
};
interface ListeningPart {
exercises: Exercise[];
text:
| {
conversation: {
gender: string;
name: string;
text: string;
voice: string;
}[];
}
| string;
}
const ListeningGeneration = () => {
const [part1, setPart1] = useState<ListeningPart>();
const [part2, setPart2] = useState<ListeningPart>();
const [part3, setPart3] = useState<ListeningPart>();
const [part4, setPart4] = useState<ListeningPart>();
const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<ListeningExam>();
const [types, setTypes] = useState<string[]>([]);
const availableTypes = [
@@ -86,8 +121,47 @@ const ListeningGeneration = () => {
{type: "writeBlanks", label: "Write the Blanks"},
];
const router = useRouter();
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const toggleType = (type: string) => setTypes((prev) => (prev.includes(type) ? [...prev.filter((x) => x !== type)] : [...prev, type]));
const submitExam = () => {
if (!part1 || !part2 || !part3 || !part4) return toast.error("Please generate all for sections!");
setIsLoading(true);
axios
.post(`/api/exam/listening/generate/listening`, {parts: [part1, part2, part3, part4]})
.then((result) => {
checkSound();
setResultingExam(result.data);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const loadExam = async (examId: string) => {
const exam = await getExamById("listening", examId.trim());
if (!exam) {
toast.error("Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID", {
toastId: "invalid-exam-id",
});
return;
}
setExams([exam]);
setSelectedModules(["listening"]);
router.push("/exercises");
};
return (
<>
<div className="flex flex-col gap-3">
@@ -121,7 +195,7 @@ const ListeningGeneration = () => {
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
)
}>
Passage 1
Section 1
</Tab>
<Tab
className={({selected}) =>
@@ -132,7 +206,7 @@ const ListeningGeneration = () => {
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
)
}>
Passage 2
Section 2
</Tab>
<Tab
className={({selected}) =>
@@ -143,7 +217,18 @@ const ListeningGeneration = () => {
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
)
}>
Passage 3
Section 3
</Tab>
<Tab
className={({selected}) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
)
}>
Section 4
</Tab>
</Tab.List>
<Tab.Panels>
@@ -151,22 +236,44 @@ const ListeningGeneration = () => {
{part: part1, setPart: setPart1},
{part: part2, setPart: setPart2},
{part: part3, setPart: setPart3},
{part: part4, setPart: setPart4},
].map(({part, setPart}, index) => (
<PartTab part={part} types={types} index={index + 1} key={index} setPart={setPart} />
))}
</Tab.Panels>
</Tab.Group>
<button
disabled={!part1 || !part2 || !part3}
data-tip="Please generate all three passages"
className={clsx(
"bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] px-6 py-6 rounded-xl h-[70px] self-end",
"hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
(!part1 || !part2 || !part3) && "tooltip",
)}>
Submit
</button>
<div className="w-full flex justify-end gap-4">
{resultingExam && (
<button
disabled={isLoading}
onClick={() => loadExam(resultingExam.id)}
className={clsx(
"bg-white border border-ielts-listening text-ielts-listening w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-listening hover:text-white disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
)}>
Perform Exam
</button>
)}
<button
disabled={!part1 || !part2 || !part3 || !part4 || isLoading}
data-tip="Please generate all three passages"
onClick={submitExam}
className={clsx(
"bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
(!part1 || !part2 || !part3 || !part4) && "tooltip",
)}>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Submit"
)}
</button>
</div>
</>
);
};

View File

@@ -15,15 +15,15 @@ const db = getFirestore(app);
export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) {
res.status(401).json({ok: false});
return;
}
if (req.method === "GET") return get(req, res);
if (req.method === "POST") return post(req, res);
if (req.session.user.type !== "developer") {
res.status(403).json({ok: false});
return;
}
return res.status(404).json({ok: false});
}
async function get(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) return res.status(401).json({ok: false});
if (req.session.user.type !== "developer") return res.status(403).json({ok: false});
const {endpoint, topic, exercises} = req.query as {module: Module; endpoint: string; topic?: string; exercises?: string[]};
const url = `${process.env.BACKEND_URL}/${endpoint}`;
@@ -34,3 +34,21 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json(result.data);
}
async function post(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) return res.status(401).json({ok: false});
if (req.session.user.type !== "developer") return res.status(403).json({ok: false});
const {endpoint, topic, exercises} = req.query as {module: Module; endpoint: string; topic?: string; exercises?: string[]};
const url = `${process.env.BACKEND_URL}/${endpoint}`;
const result = await axios.post(
`${url}${topic && exercises ? `?topic=${topic.toLowerCase()}&exercises=${exercises.join("&exercises=")}` : ""}`,
req.body,
{
headers: {Authorization: `Bearer ${process.env.BACKEND_JWT}`},
},
);
res.status(200).json(result.data);
}

9
src/utils/sound.ts Normal file
View File

@@ -0,0 +1,9 @@
import {Howl, Howler} from "howler";
export const checkSound = () => {
const sound = new Howl({
src: ["audio/check.mp3"],
});
sound.play();
};