Skip to content

Commit 5813427

Browse files
Merge pull request #86 from abhitrueprogrammer/staging
chore: Seperated the mapping of AI tags to pre declared ones into a function
2 parents 9922ce3 + c3e6e19 commit 5813427

File tree

7 files changed

+83
-50
lines changed

7 files changed

+83
-50
lines changed

src/app/api/ai-upload/route.ts

Lines changed: 63 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,19 @@ import { NextResponse } from "next/server";
22
import { PDFDocument } from "pdf-lib";
33
import {
44
campuses,
5+
courses,
6+
exams,
57
semesters,
68
slots,
79
years,
810
} from "@/components/select_options";
911
import { connectToDatabase } from "@/lib/mongoose";
1012
import cloudinary from "cloudinary";
11-
import { type ICourses, type CloudinaryUploadResult } from "@/interface";
13+
import type {
14+
ICourses,
15+
CloudinaryUploadResult,
16+
ExamDetail,
17+
} from "@/interface";
1218
import { PaperAdmin } from "@/db/papers";
1319
import axios from "axios";
1420
import processAndAnalyze from "@/util/mistral";
@@ -38,53 +44,34 @@ export async function POST(req: Request) {
3844
} else {
3945
const bytes = await files[0]?.arrayBuffer();
4046
if (bytes) {
41-
const buffer = Buffer.from(bytes);
47+
const buffer = Buffer.from(bytes);
4248
imageURL = `data:${"image/png"};base64,${buffer.toString("base64")}`;
4349
}
4450
}
4551
const tags = await processAndAnalyze({ imageURL });
46-
let subject = "";
47-
let slot = "";
48-
let exam = "";
49-
let year = "";
50-
let campus = "";
51-
let semester = "";
52-
const { data } = await axios.get<ICourses[]>(
53-
`${process.env.SERVER_URL}/api/course-list`,
54-
);
55-
const courses = data.map((course: { name: string }) => course.name);
56-
const coursesFuzy = new Fuse(courses);
57-
if (!tags) {
58-
console.log("Anaylsis failed, inputing blank strings as fields");
59-
} else {
60-
const subjectSearch = coursesFuzy.search(tags["course-name"])[0];
61-
if (subjectSearch) {
62-
subject = subjectSearch.item;
63-
}
64-
const slotPattern = new RegExp(`[${tags.slot}]`, "i");
65-
const slotSearchResult = slots.find((s) => slotPattern.test(s));
66-
slot = slotSearchResult ? slotSearchResult : tags.slot;
67-
if ("exam-type" in tags && tags["exam-type"] in examMap) {
68-
const examType = tags["exam-type"] as keyof typeof examMap;
69-
exam = examMap[examType];
70-
}
71-
year = formData.get("year") as string;
72-
campus = formData.get("campus") as string;
73-
semester = formData.get("semester") as string;
74-
}
75-
console.log(exam, slot, subject);
52+
const finalTags = await setTagsFromCurrentLists(tags);
53+
console.log(finalTags)
54+
const subject = finalTags["course-name"];
55+
const slot = finalTags.slot;
56+
const exam = finalTags["exam-type"];
57+
const year = formData.get("year") as string;
58+
const campus = formData.get("campus") as string;
59+
const semester =formData.get("semester") as string;
7660

61+
62+
console.log(subject , slot, exam)
7763
if (
7864
!(
65+
courses.includes(subject) &&
66+
slots.includes(slot) &&
7967
exam.includes(exam) &&
8068
years.includes(year) &&
8169
campuses.includes(campus) &&
8270
semesters.includes(semester)
8371
)
8472
) {
85-
return NextResponse.json({ message: "Bad request" }, { status: 400 });
73+
return NextResponse.json({ message: "Bad request/AI couldn't set tags" }, { status: 400 });
8674
}
87-
8875
await connectToDatabase();
8976
let finalUrl: string | undefined = "";
9077
let public_id_cloudinary: string | undefined = "";
@@ -213,3 +200,45 @@ async function CreatePDF(files: File[]) {
213200
const mergedPdfBytes = await pdfDoc.save();
214201
return mergedPdfBytes;
215202
}
203+
204+
//sets course-name to corresponding course name from our api
205+
async function setTagsFromCurrentLists(
206+
tags: ExamDetail | undefined,
207+
): Promise<ExamDetail> {
208+
const { data } = await axios.get<ICourses[]>(
209+
`${process.env.SERVER_URL}/api/course-list`,
210+
);
211+
const courses = data.map((course: { name: string }) => course.name);
212+
if (!courses[0] || !slots[0] || !exams[0]) {
213+
throw "Cannot fetch default value for courses/slot/exam!";
214+
}
215+
const newTags: ExamDetail = {
216+
"course-name": courses[0],
217+
slot: slots[0],
218+
"course-code": "notInUse",
219+
"exam-type": exams[0],
220+
};
221+
const coursesFuzy = new Fuse(courses);
222+
if (!tags) {
223+
console.log("Anaylsis failed setting random courses as fields");
224+
return newTags;
225+
} else {
226+
const subjectSearch = coursesFuzy.search(
227+
tags["course-name"] + "|" + tags["course-code"],
228+
)[0];
229+
if (subjectSearch) {
230+
newTags["course-name"] = subjectSearch.item;
231+
}
232+
const slotPattern = new RegExp(`[${tags.slot}]`, "i");
233+
const slotSearchResult = slots.find((s) => slotPattern.test(s));
234+
if(slotSearchResult)
235+
{
236+
newTags.slot = slotSearchResult
237+
}
238+
if ("exam-type" in tags && tags["exam-type"] in examMap) {
239+
const examType = tags["exam-type"] as keyof typeof examMap;
240+
newTags["exam-type"] = examMap[examType];
241+
}
242+
}
243+
return newTags;
244+
}

src/app/paper/[id]/page.tsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,9 +138,12 @@ const PaperPage = async ({ params }: { params: { id: string } }) => {
138138
} else {
139139
return errorResponse?.data?.message ?? "Failed to fetch paper";
140140
}
141+
} else if (err instanceof Error) {
142+
return err.message;
141143
} else {
142-
return `${err}`;
144+
return String(err);
143145
}
146+
144147
}
145148
}
146149
const paper = await getPaper();

src/app/upload/page.tsx

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,9 @@ const Page = () => {
8383
return;
8484
}
8585
if (!campus) {
86-
toast.error("Campus is required");
87-
return;
86+
setCampus("Vellore")
87+
// toast.error("Campus is required");
88+
// return;
8889
}
8990
if (!semester) {
9091
toast.error("Semester is required");
@@ -194,9 +195,8 @@ const Page = () => {
194195
</Select>
195196
</div>
196197

197-
{/* Year Selection */}
198198
<div>
199-
<label>Campus:</label>
199+
{/* <label>Campus:</label>
200200
<Select value={campus} onValueChange={setCampus}>
201201
<SelectTrigger className="m-2 rounded-md border p-2">
202202
<SelectValue placeholder="Select campus" />
@@ -211,7 +211,7 @@ const Page = () => {
211211
))}
212212
</SelectGroup>
213213
</SelectContent>
214-
</Select>
214+
</Select> */}
215215
</div>
216216
<div>
217217
<label>Semester:</label>

src/components/Card.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ const Card = ({
7979
{capsule(paper.exam)}
8080
{capsule(paper.slot)}
8181
{capsule(paper.year)}
82-
{capsule(paper.campus)}
82+
{/* {capsule(paper.campus)} */}
8383
{capsule(paper.semester)}
8484
{paper.answerKeyIncluded && capsuleGreen("Answer key included")}
8585
</div>

src/components/FilterDialog.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,12 +132,12 @@ export const FilterDialog = ({
132132
placeholder="Semesters"
133133
defaultValue={selectedSemesters}
134134
/>
135-
<MultiSelect
135+
{/* <MultiSelect
136136
options={campuses}
137137
onValueChange={setSelectedCampuses}
138138
placeholder="Campuses"
139139
defaultValue={selectedCampuses}
140-
/>
140+
/> */}
141141
</div>
142142
<div className="flex justify-between">
143143
<Button variant="outline" onClick={handleFilterClick}>

src/interface.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,12 @@ export interface IPaper {
145145
year: string;
146146
answerKeyIncluded?: boolean;
147147
}
148-
148+
export type ExamDetail = {
149+
"course-name": string;
150+
slot: string;
151+
"course-code": string;
152+
"exam-type": string;
153+
};
149154
export interface Filters {
150155
papers: IPaper[];
151156
uniqueExams: string[];

src/util/mistral.ts

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,10 @@ import '@ungap/with-resolvers';
22

33

44
import { Mistral } from "@mistralai/mistralai";
5+
import {type ExamDetail } from '@/interface';
56

67
// Type definitions
7-
type ExamDetail = {
8-
"course-name": string;
9-
slot: string;
10-
"course-code": string;
11-
"exam-type": string;
12-
};
8+
139

1410
type AnalysisResult = {
1511
examDetail: ExamDetail;

0 commit comments

Comments
 (0)