Spaces:
Running on Zero

khmersense / frontend /src /api.ts
vechey's picture
Deploy KhmerSense
3a260a9 verified
Raw History Blame Contribute Delete
2.5 kB
import type { Health, Item, Result } from "./types";
async function request<T>(path: string, init?: RequestInit): Promise<T> {
let res: Response;
try {
res = await fetch(path, init);
} catch {
throw new Error("Can't reach the KhmerSense server. Is the backend running?");
}
const body = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(typeof body.detail === "string" ? body.detail : `Something went wrong (${res.status}).`);
return body as T;
}
const json = (data: unknown): RequestInit => ({
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
export const api = {
health: () => request<Health>("/api/health"),
analyzeTexts: (texts: string[]) => request<Result>("/api/analyze", json({ texts })),
analyzeYouTube: (url: string, limit: number, order: "relevance" | "time") =>
request<Result>("/api/youtube", json({ url, limit, order })),
analyzeFile: (file: File) => {
const fd = new FormData();
fd.append("file", file);
return request<Result>("/api/upload", { method: "POST", body: fd });
},
};
/** CSV with a UTF-8 BOM so Excel shows Khmer correctly. */
export function downloadCsv(items: Item[], name: string) {
const esc = (v: unknown) => `"${String(v ?? "").replace(/"/g, '""')}"`;
const head = ["comment", "sentiment", "confidence", "language", "likes", "date"];
const rows = items.map((i) => [i.text, i.label, i.confidence, i.language, i.likes ?? "", i.published_at ?? ""].map(esc).join(","));
const blob = new Blob(["๏ปฟ" + [head.join(","), ...rows].join("\r\n")], { type: "text/csv;charset=utf-8" });
const a = Object.assign(document.createElement("a"), { href: URL.createObjectURL(blob), download: name });
a.click();
URL.revokeObjectURL(a.href);
}
export const SAMPLE_COMMENTS = [
"แžœแžธแžŠแŸแžขแžผแž“แŸแŸ‡แž›แŸ’แžขแžŽแžถแžŸแŸ‹ แžขแžšแž‚แžปแžŽแž”แž„แŸ—",
"This video is so helpful, thank you!",
"แžŸแŸ†แžกแŸแž„แžแžทแž…แž–แŸแž€ แžŸแŸ’แžแžถแž”แŸ‹แž˜แžทแž“แžŸแžผแžœแžฎแž‘แŸ",
"video แž›แŸ’แžขแžŽแžถแžŸแŸ‹ bro ๐Ÿ‘",
"Waste of time, the title is clickbait",
"แž–แŸแž›แžŽแžถแž…แŸแž‰แž—แžถแž‚แž”แž“แŸ’แž‘แžถแž”แŸ‹?",
"Love the editing and the music ๐Ÿ˜",
"แž˜แžทแž“แž›แŸ’แžขแž‘แŸ แž’แžปแž‰แžŽแžถแžŸแŸ‹",
"ok",
"แž”แž„แž–แžผแž€แŸ‚แžŽแžถแžŸแŸ‹ แž…แž„แŸ‹แžšแŸ€แž“แž”แž“แŸ’แžแŸ‚แž˜แž‘แŸ€แž",
"The sound quality is bad in the second half",
"Where was this filmed?",
];