first commit

This commit is contained in:
2026-06-10 18:30:46 +02:00
parent 3e7b0ae2e0
commit cabd4803a4
39 changed files with 3635 additions and 81 deletions
+47
View File
@@ -0,0 +1,47 @@
import { and, eq } from "drizzle-orm";
import type { CardType } from "./cards";
import { getDb } from "./db";
import { cardCache } from "./db/schema";
export async function getCachedCard<T>(
movieId: number,
cardType: CardType,
): Promise<T | null> {
const db = getDb();
const rows = await db
.select()
.from(cardCache)
.where(
and(eq(cardCache.movieId, movieId), eq(cardCache.cardType, cardType)),
)
.limit(1);
if (rows.length === 0) {
return null;
}
return rows[0].payload as T;
}
export async function setCachedCard<T>(
movieId: number,
cardType: CardType,
payload: T,
): Promise<void> {
const db = getDb();
await db
.insert(cardCache)
.values({
movieId,
cardType,
payload,
})
.onConflictDoUpdate({
target: [cardCache.movieId, cardCache.cardType],
set: {
payload,
createdAt: new Date(),
},
});
}
+116
View File
@@ -0,0 +1,116 @@
import type { CardType } from "./cards";
import { getCachedCard, setCachedCard } from "./cache";
import { generateStructuredResponse } from "./llm";
import {
historicalAccuracySchema,
internationalRatingsSchema,
productionFactsSchema,
ratingExplainedSchema,
sensitivityGuideSchema,
skipGuideSchema,
} from "./schemas";
import { formatMovieContext, getMovieDetails } from "./tmdb";
const PROMPTS: Record<CardType, string> = {
rating_explained: `Analyze why this film received its age rating.
You MUST return ONLY valid JSON matching this exact structure (no extra keys, no markdown):
{
"officialRating": string,
"region": string,
"summary": string,
"factors": array of {
"category": one of exactly ["violence", "language", "sexuality", "substances", "frightening", "other"] (use ONLY these strings, no synonyms like "gore" or "nudity" — map to closest),
"intensity": one of exactly ["mild", "moderate", "strong"],
"description": string,
"approximateTiming": string (optional, e.g. "12:45"),
"confidence": one of ["high", "medium", "low"] (optional)
},
"borderlineNote": string (optional)
}
Focus on specific scenes or content patterns that drove the rating. Be precise with the allowed category and intensity values.`,
skip_guide: `Create a skip guide for families who want to watch this film with a younger audience.
You MUST return ONLY valid JSON matching this exact structure:
{
"originalRating": string,
"suggestedAudienceAge": number (integer 0-21),
"totalSkippedMinutes": number (integer),
"segments": array of {
"start": string (e.g. "0:05" or "12m"),
"end": string,
"reason": string,
"intensity": one of exactly ["mild", "moderate", "strong"],
"plotImpact": one of exactly ["none", "minor", "significant"],
"skipRecommendation": one of exactly ["recommended", "optional", "do_not_skip"],
"resumeHint": string
},
"disclaimer": string
}
Only include genuinely skippable segments. Mark plot-critical scenes as skipRecommendation "do_not_skip".
Timestamps should be approximate for the standard theatrical cut. Use only the exact enum strings listed.`,
sensitivity_guide: `Create a sensitivity guide grouping potentially upsetting content by theme.
You MUST return ONLY valid JSON:
{
"summary": string,
"themes": array of {
"theme": string,
"severity": one of exactly ["mild", "moderate", "strong"],
"description": string,
"approximateTiming": string (optional)
}
}
Cover violence, sexuality, substances, self-harm, abuse, animal harm, discrimination, and other difficult themes where relevant. Use only the exact "severity" values.`,
international_ratings: `Summarize how this film is rated across countries using the certification data provided.
Return JSON with: ratings (array of {country, countryCode, rating, descriptors?}), discrepancyNote, strictestCountry (optional), mostLenientCountry (optional).
Include at least US, GB, ES, DE, FR when data exists. Explain notable differences.`,
production_facts: `Curate interesting behind-the-scenes production facts for cinephiles.
Return JSON with: facts (array of at least 5 {category, fact}), budget (optional string), boxOffice (optional string), filmingLocations (optional array of strings).
Prefer specific, verifiable-sounding details; note uncertainty in the fact text when needed.`,
historical_accuracy: `Evaluate historical accuracy for this biographical or historical film.
You MUST return ONLY valid JSON:
{
"accuracyScore": number (0-100),
"summary": string,
"accurateElements": string[],
"inventions": array of { "claim": string, "reality": string },
"confidence": one of exactly ["high", "medium", "low"]
}
If the film is not historical/biographical, still assess any real-world basis it claims. Use only the exact confidence value.`,
};
const SCHEMAS = {
rating_explained: ratingExplainedSchema,
skip_guide: skipGuideSchema,
sensitivity_guide: sensitivityGuideSchema,
international_ratings: internationalRatingsSchema,
production_facts: productionFactsSchema,
historical_accuracy: historicalAccuracySchema,
} as const;
export async function generateCard(movieId: number, cardType: CardType) {
const cached = await getCachedCard(movieId, cardType);
if (cached) {
const schema = SCHEMAS[cardType];
if (schema.safeParse(cached).success) {
return { data: cached, cached: true };
}
// stale/invalid cached data (e.g. from before prompt/schema tightening) — regenerate
}
const movie = await getMovieDetails(movieId);
const context = formatMovieContext(movie);
const prompt = `${PROMPTS[cardType]}
Movie context:
${context}`;
const schema = SCHEMAS[cardType];
const data = await generateStructuredResponse(schema, prompt);
await setCachedCard(movieId, cardType, data);
return { data, cached: false };
}
+59
View File
@@ -0,0 +1,59 @@
export const CARD_TYPES = [
"rating_explained",
"skip_guide",
"sensitivity_guide",
"international_ratings",
"production_facts",
"historical_accuracy",
] as const;
export type CardType = (typeof CARD_TYPES)[number];
export interface CardMeta {
title: string;
subtitle: string;
badge?: string;
}
export const CARD_META: Record<CardType, CardMeta> = {
rating_explained: {
title: "Rating Explained",
subtitle: "Why this film has its age rating",
},
skip_guide: {
title: "Skip Guide",
subtitle: "Scenes you can skip for a younger audience",
badge: "Families",
},
sensitivity_guide: {
title: "Sensitivity Guide",
subtitle: "Content warnings by theme",
},
international_ratings: {
title: "International Ratings",
subtitle: "How ratings differ by country",
},
production_facts: {
title: "Production Facts",
subtitle: "Behind-the-scenes facts",
},
historical_accuracy: {
title: "Historical Accuracy",
subtitle: "Fact vs fiction breakdown",
},
};
const HISTORICAL_GENRES = new Set([
"history",
"war",
"biography",
"documentary",
]);
export function shouldShowHistoricalAccuracy(genres: string[]): boolean {
return genres.some((genre) => HISTORICAL_GENRES.has(genre.toLowerCase()));
}
export function isCardType(value: string): value is CardType {
return CARD_TYPES.includes(value as CardType);
}
+36
View File
@@ -0,0 +1,36 @@
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import * as schema from "./schema";
const connectionString = process.env.DATABASE_URL;
let client: ReturnType<typeof postgres> | null = null;
let db: ReturnType<typeof drizzle<typeof schema>> | null = null;
export function getDb() {
if (!connectionString) {
throw new Error("DATABASE_URL is not set");
}
if (!client) {
client = postgres(connectionString, { max: 10 });
db = drizzle(client, { schema });
}
return db!;
}
export async function checkDbConnection(): Promise<boolean> {
if (!connectionString) {
return false;
}
try {
const probe = postgres(connectionString, { max: 1 });
await probe`SELECT 1`;
await probe.end();
return true;
} catch {
return false;
}
}
+28
View File
@@ -0,0 +1,28 @@
import {
integer,
jsonb,
pgTable,
serial,
timestamp,
uniqueIndex,
varchar,
} from "drizzle-orm/pg-core";
export const cardCache = pgTable(
"card_cache",
{
id: serial("id").primaryKey(),
movieId: integer("movie_id").notNull(),
cardType: varchar("card_type", { length: 50 }).notNull(),
payload: jsonb("payload").notNull(),
createdAt: timestamp("created_at", { withTimezone: true })
.defaultNow()
.notNull(),
},
(table) => [
uniqueIndex("card_cache_movie_card_unique").on(
table.movieId,
table.cardType,
),
],
);
+69
View File
@@ -0,0 +1,69 @@
import { z } from "zod";
const SYSTEM_PROMPT = `You are a film research assistant for an international audience.
You MUST respond in English with valid JSON only — no markdown fences, no commentary.
Use a clear, neutral tone. If uncertain about a scene or timestamp, state uncertainty and set confidence to "low".
Do not invent scenes, quotes, or timestamps. Base answers on the movie context provided.`;
export async function generateStructuredResponse<T extends z.ZodType>(
schema: T,
userPrompt: string,
): Promise<z.infer<T>> {
const apiKey = process.env.LLM_API_KEY;
if (!apiKey) {
throw new Error("LLM_API_KEY is not set");
}
const baseUrl = process.env.LLM_BASE_URL ?? "https://api.openai.com/v1";
const model = process.env.LLM_MODEL ?? "gpt-4o-mini";
const headers: Record<string, string> = {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
};
if (process.env.LLM_HTTP_REFERER) {
headers["HTTP-Referer"] = process.env.LLM_HTTP_REFERER;
}
if (process.env.LLM_APP_TITLE) {
headers["X-Title"] = process.env.LLM_APP_TITLE;
}
const response = await fetch(`${baseUrl}/chat/completions`, {
method: "POST",
headers,
body: JSON.stringify({
model,
temperature: 0.2,
response_format: { type: "json_object" },
messages: [
{ role: "system", content: SYSTEM_PROMPT },
{ role: "user", content: userPrompt },
],
}),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`LLM request failed: ${response.status} ${errorText}`);
}
const data = (await response.json()) as {
choices: Array<{ message: { content: string } }>;
};
const content = data.choices[0]?.message?.content;
if (!content) {
throw new Error("LLM returned empty content");
}
let parsed: unknown;
try {
parsed = JSON.parse(content);
} catch {
throw new Error("LLM returned invalid JSON");
}
return schema.parse(parsed);
}
+103
View File
@@ -0,0 +1,103 @@
import { z } from "zod";
const intensity = z.enum(["mild", "moderate", "strong"]);
const confidence = z.enum(["high", "medium", "low"]);
export const ratingExplainedSchema = z.object({
officialRating: z.string(),
region: z.string(),
summary: z.string(),
factors: z.array(
z.object({
category: z.enum([
"violence",
"language",
"sexuality",
"substances",
"frightening",
"other",
]),
intensity,
description: z.string(),
approximateTiming: z.string().optional(),
confidence: confidence.optional(),
}),
),
borderlineNote: z.string().optional(),
});
export const skipGuideSchema = z.object({
originalRating: z.string(),
suggestedAudienceAge: z.number().int().min(0).max(21),
totalSkippedMinutes: z.number().int().min(0),
segments: z.array(
z.object({
start: z.string(),
end: z.string(),
reason: z.string(),
intensity,
plotImpact: z.enum(["none", "minor", "significant"]),
skipRecommendation: z.enum(["recommended", "optional", "do_not_skip"]),
resumeHint: z.string(),
}),
),
disclaimer: z.string(),
});
export const sensitivityGuideSchema = z.object({
summary: z.string(),
themes: z.array(
z.object({
theme: z.string(),
severity: intensity,
description: z.string(),
approximateTiming: z.string().optional(),
}),
),
});
export const internationalRatingsSchema = z.object({
ratings: z.array(
z.object({
country: z.string(),
countryCode: z.string(),
rating: z.string(),
descriptors: z.array(z.string()).optional(),
}),
),
discrepancyNote: z.string(),
strictestCountry: z.string().optional(),
mostLenientCountry: z.string().optional(),
});
export const productionFactsSchema = z.object({
facts: z.array(
z.object({
category: z.string(),
fact: z.string(),
}),
),
budget: z.string().optional(),
boxOffice: z.string().optional(),
filmingLocations: z.array(z.string()).optional(),
});
export const historicalAccuracySchema = z.object({
accuracyScore: z.number().min(0).max(100),
summary: z.string(),
accurateElements: z.array(z.string()),
inventions: z.array(
z.object({
claim: z.string(),
reality: z.string(),
}),
),
confidence,
});
export type RatingExplained = z.infer<typeof ratingExplainedSchema>;
export type SkipGuide = z.infer<typeof skipGuideSchema>;
export type SensitivityGuide = z.infer<typeof sensitivityGuideSchema>;
export type InternationalRatings = z.infer<typeof internationalRatingsSchema>;
export type ProductionFacts = z.infer<typeof productionFactsSchema>;
export type HistoricalAccuracy = z.infer<typeof historicalAccuracySchema>;
+157
View File
@@ -0,0 +1,157 @@
const TMDB_BASE = "https://api.themoviedb.org/3";
const LANGUAGE = "en-US";
export interface TmdbSearchResult {
id: number;
title: string;
release_date: string;
poster_path: string | null;
overview: string;
}
export interface TmdbMovieDetails {
id: number;
title: string;
release_date: string;
runtime: number | null;
overview: string;
poster_path: string | null;
backdrop_path: string | null;
genres: Array<{ id: number; name: string }>;
budget: number;
revenue: number;
production_countries: Array<{ iso_3166_1: string; name: string }>;
production_companies: Array<{ name: string }>;
spoken_languages: Array<{ english_name: string }>;
release_dates?: {
results: Array<{
iso_3166_1: string;
release_dates: Array<{
certification: string;
type: number;
note: string;
}>;
}>;
};
keywords?: {
keywords: Array<{ id: number; name: string }>;
};
credits?: {
cast: Array<{ name: string; character: string }>;
crew: Array<{ name: string; job: string; department: string }>;
};
}
function getApiKey(): string {
const key = process.env.TMDB_API_KEY;
if (!key) {
throw new Error("TMDB_API_KEY is not set");
}
return key;
}
async function tmdbFetch<T>(path: string, params: Record<string, string> = {}) {
const url = new URL(`${TMDB_BASE}${path}`);
url.searchParams.set("api_key", getApiKey());
url.searchParams.set("language", LANGUAGE);
for (const [key, value] of Object.entries(params)) {
url.searchParams.set(key, value);
}
const response = await fetch(url.toString(), {
next: { revalidate: 3600 },
});
if (!response.ok) {
throw new Error(`TMDB request failed: ${response.status}`);
}
return response.json() as Promise<T>;
}
export async function searchMovies(query: string): Promise<TmdbSearchResult[]> {
if (!query.trim()) {
return [];
}
const data = await tmdbFetch<{ results: TmdbSearchResult[] }>("/search/movie", {
query: query.trim(),
include_adult: "false",
});
return data.results.slice(0, 8);
}
export async function getMovieDetails(movieId: number): Promise<TmdbMovieDetails> {
return tmdbFetch<TmdbMovieDetails>(`/movie/${movieId}`, {
append_to_response: "release_dates,credits,keywords",
});
}
export function getPosterUrl(path: string | null, size: "w185" | "w500" | "original" = "w500") {
if (!path) {
return null;
}
return `https://image.tmdb.org/t/p/${size}${path}`;
}
export function getUsCertification(movie: TmdbMovieDetails): string | null {
const us = movie.release_dates?.results.find((r) => r.iso_3166_1 === "US");
if (!us) {
return null;
}
const theatrical = us.release_dates.find((r) => r.type === 3 && r.certification);
if (theatrical?.certification) {
return theatrical.certification;
}
const any = us.release_dates.find((r) => r.certification);
return any?.certification ?? null;
}
export function formatMovieContext(movie: TmdbMovieDetails): string {
const genres = movie.genres.map((g) => g.name).join(", ");
const keywords = movie.keywords?.keywords.map((k) => k.name).join(", ") ?? "";
const certification = getUsCertification(movie);
const directors = movie.credits?.crew
.filter((c) => c.job === "Director")
.map((c) => c.name)
.join(", ");
const leadCast = movie.credits?.cast
.slice(0, 5)
.map((c) => `${c.name} as ${c.character}`)
.join("; ");
const releaseDates = movie.release_dates?.results
.map((country) => {
const certs = country.release_dates
.filter((r) => r.certification)
.map((r) => r.certification);
const unique = [...new Set(certs)];
if (unique.length === 0) {
return null;
}
return `${country.iso_3166_1}: ${unique.join(", ")}`;
})
.filter(Boolean)
.join("\n");
return [
`Title: ${movie.title}`,
`Year: ${movie.release_date?.slice(0, 4) ?? "Unknown"}`,
`Runtime: ${movie.runtime ?? "Unknown"} minutes`,
`Genres: ${genres}`,
`Overview: ${movie.overview}`,
certification ? `US Certification: ${certification}` : null,
keywords ? `Keywords: ${keywords}` : null,
directors ? `Director(s): ${directors}` : null,
leadCast ? `Lead cast: ${leadCast}` : null,
movie.budget ? `Budget: $${movie.budget.toLocaleString("en-US")}` : null,
movie.revenue ? `Revenue: $${movie.revenue.toLocaleString("en-US")}` : null,
releaseDates ? `International certifications:\n${releaseDates}` : null,
]
.filter(Boolean)
.join("\n");
}
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}