mirror of
https://github.com/Dasemu/si-no-o-indiferente.git
synced 2026-11-26 07:16:19 +00:00
Add player difficulty ratings, drop hint system, use Peninsular Spanish in Gemini prompt
Players can now submit a voluntary 1-5 difficulty rating after a story ends (POST /api/stories/:id/ratings), stored in data/ratings.json. A new reclassifyDifficulty script (wired to a weekly systemd timer) averages those ratings and adjusts a story's difficulty band once it has enough votes. The progressive hint system is removed end-to-end (schema, Gemini prompt/response schema, generation instructions), and the Gemini prompt is rewritten in Peninsular Spanish with an explicit instruction to generate story content in Spain Spanish rather than any LatAm variant. Also translates remaining Spanish code comments/error strings to English and updates the backend README and systemd units accordingly.
This commit is contained in:
1 parent
7f3e6cc839
commit
99a903f6e1
20 files changed
+275
-97
No files matched your search
+13
-9
@@ -1,21 +1,25 @@
|
||||
# Puerto donde escucha la API
|
||||
# Port the API listens on
|
||||
PORT=8787
|
||||
|
||||
# Origen permitido para CORS (la URL desde donde se sirve el frontend/PWA).
|
||||
# Usa "*" solo en desarrollo.
|
||||
# Allowed CORS origin (the URL the frontend/PWA is served from).
|
||||
# Use "*" only in development.
|
||||
CORS_ORIGIN=*
|
||||
|
||||
# API key de Google Gemini (https://aistudio.google.com/apikey)
|
||||
# Google Gemini API key (https://aistudio.google.com/apikey)
|
||||
GEMINI_API_KEY=
|
||||
|
||||
# Modelo de Gemini a usar para generar historias
|
||||
# Gemini model used to generate stories
|
||||
GEMINI_MODEL=gemini-2.5-flash
|
||||
|
||||
# Cuantas historias nuevas generar por dia
|
||||
# How many new stories to generate per day
|
||||
STORIES_PER_DAY=5
|
||||
|
||||
# Carpeta donde se guardan las historias generadas (JSON), relativa al backend
|
||||
# Folder where generated stories (JSON) are stored, relative to the backend
|
||||
DATA_DIR=./data
|
||||
|
||||
# Token secreto para poder disparar la generacion manualmente via POST /api/admin/generate
|
||||
ADMIN_TOKEN=cambia-este-token
|
||||
# Secret token to manually trigger generation via POST /api/admin/generate
|
||||
ADMIN_TOKEN=change-this-token
|
||||
|
||||
# Minimum number of player ratings a story needs before the periodic
|
||||
# reclassification job will adjust its difficulty
|
||||
MIN_RATINGS_FOR_RECLASSIFICATION=3
|
||||
+33
-21
@@ -1,39 +1,51 @@
|
||||
# Backend — Historias Incompletas
|
||||
# Backend — Sí, no, o indiferente
|
||||
|
||||
API en Node/Express (TypeScript) que sirve el mazo de historias "actualizado"
|
||||
y lo regenera una vez al día llamando a la API de Gemini.
|
||||
Node/Express (TypeScript) API that serves the "updated" story deck and
|
||||
regenerates it once a day by calling the Gemini API.
|
||||
|
||||
## Endpoints
|
||||
|
||||
- `GET /api/health` — chequeo de salud.
|
||||
- `GET /api/stories` — último lote de historias generado. `204` si todavía
|
||||
no se generó ninguno (el cliente debe usar su set default en ese caso).
|
||||
- `POST /api/admin/generate` — dispara una generación manual con Gemini.
|
||||
Requiere header `x-admin-token` igual a `ADMIN_TOKEN`.
|
||||
- `GET /api/health` — health check.
|
||||
- `GET /api/stories` — latest generated story batch. `204` if none has been
|
||||
generated yet (the client should fall back to its default set in that
|
||||
case).
|
||||
- `POST /api/admin/generate` — triggers a manual generation with Gemini.
|
||||
Requires an `x-admin-token` header matching `ADMIN_TOKEN`.
|
||||
- `POST /api/stories/:id/ratings` — records a player's voluntary 1-5
|
||||
difficulty rating for a story (`{ "rating": 1-5 }` body). Open endpoint,
|
||||
no auth required. Works for any story id, including ones from the
|
||||
frontend's embedded default set.
|
||||
|
||||
## Desarrollo
|
||||
## Development
|
||||
|
||||
```bash
|
||||
npm install
|
||||
cp .env.example .env # completa GEMINI_API_KEY y ADMIN_TOKEN
|
||||
cp .env.example .env # fill in GEMINI_API_KEY and ADMIN_TOKEN
|
||||
npm run dev # http://localhost:8787
|
||||
npm run generate # genera un lote nuevo a mano (llama a Gemini de verdad)
|
||||
npm run generate # generates a new batch by hand (calls Gemini for real)
|
||||
npm run reclassify # reclassifies difficulty from collected ratings by hand
|
||||
```
|
||||
|
||||
## Producción
|
||||
## Production
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
npm start # corre dist/index.js
|
||||
npm run generate:built # corre dist/scripts/generateDaily.js (lo usa el systemd timer)
|
||||
npm start # runs dist/index.js
|
||||
npm run generate:built # runs dist/scripts/generateDaily.js (used by the systemd timer)
|
||||
npm run reclassify:built # runs dist/scripts/reclassifyDifficulty.js (used by the systemd timer)
|
||||
```
|
||||
|
||||
Ver [`../docs/DEPLOY.md`](../docs/DEPLOY.md) para el setup completo con
|
||||
systemd + nginx en un LXC de Debian.
|
||||
See the example unit files in `../deploy/` for the systemd + nginx setup.
|
||||
|
||||
## Almacenamiento
|
||||
## Storage
|
||||
|
||||
Las historias generadas se guardan como JSON plano en `data/` (configurable
|
||||
con `DATA_DIR`): un archivo por día (`YYYY-MM-DD.json`) y `latest.json`, que
|
||||
es lo que sirve `GET /api/stories`. No hay base de datos — a este volumen
|
||||
(5 historias/día) un archivo JSON con escritura atómica alcanza y sobra.
|
||||
Generated stories are stored as plain JSON files in `data/` (configurable
|
||||
via `DATA_DIR`): one file per day (`YYYY-MM-DD.json`) plus `latest.json`,
|
||||
which is what `GET /api/stories` serves. There's no database — at this
|
||||
volume (5 stories/day) a JSON file with atomic writes is more than enough.
|
||||
|
||||
Player difficulty ratings are appended to `data/ratings.json` as they come
|
||||
in. The `reclassifyDifficulty` script (run periodically via
|
||||
`story-reclassify.timer`) averages the ratings for each story and, once a
|
||||
story has at least `MIN_RATINGS_FOR_RECLASSIFICATION` votes, updates its
|
||||
difficulty band in `latest.json` if the average points to a different one.
|
||||
@@ -12,7 +12,9 @@
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"start": "node dist/index.js",
|
||||
"generate": "tsx src/scripts/generateDaily.ts",
|
||||
"generate:built": "node dist/scripts/generateDaily.js"
|
||||
"generate:built": "node dist/scripts/generateDaily.js",
|
||||
"reclassify": "tsx src/scripts/reclassifyDifficulty.ts",
|
||||
"reclassify:built": "node dist/scripts/reclassifyDifficulty.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"cors": "^2.8.5",
|
||||
|
||||
@@ -4,7 +4,7 @@ import path from "node:path";
|
||||
function required(name: string, value: string | undefined, fallback?: string): string {
|
||||
if (value && value.length > 0) return value;
|
||||
if (fallback !== undefined) return fallback;
|
||||
throw new Error(`Falta la variable de entorno ${name}`);
|
||||
throw new Error(`Missing environment variable ${name}`);
|
||||
}
|
||||
|
||||
export const config = {
|
||||
@@ -14,5 +14,6 @@ export const config = {
|
||||
geminiModel: process.env.GEMINI_MODEL ?? "gemini-2.5-flash",
|
||||
storiesPerDay: Number(process.env.STORIES_PER_DAY ?? 5),
|
||||
dataDir: path.resolve(process.cwd(), process.env.DATA_DIR ?? "./data"),
|
||||
adminToken: required("ADMIN_TOKEN", process.env.ADMIN_TOKEN, "cambia-este-token"),
|
||||
adminToken: required("ADMIN_TOKEN", process.env.ADMIN_TOKEN, "change-this-token"),
|
||||
minRatingsForReclassification: Number(process.env.MIN_RATINGS_FOR_RECLASSIFICATION ?? 3),
|
||||
};
|
||||
+17
-17
@@ -4,7 +4,7 @@ import { GeminiStoryBatchSchema, type Story } from "./storySchema.js";
|
||||
const GEMINI_ENDPOINT = (model: string) =>
|
||||
`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`;
|
||||
|
||||
// Subconjunto de OpenAPI que acepta el "structured output" de Gemini.
|
||||
// Subset of OpenAPI accepted by Gemini's "structured output".
|
||||
const RESPONSE_SCHEMA = {
|
||||
type: "OBJECT",
|
||||
properties: {
|
||||
@@ -18,10 +18,9 @@ const RESPONSE_SCHEMA = {
|
||||
difficulty: { type: "STRING", enum: ["easy", "medium", "hard"] },
|
||||
tags: { type: "ARRAY", items: { type: "STRING" } },
|
||||
teaser: { type: "STRING" },
|
||||
hints: { type: "ARRAY", items: { type: "STRING" } },
|
||||
solution: { type: "STRING" },
|
||||
},
|
||||
required: ["id", "title", "difficulty", "tags", "teaser", "hints", "solution"],
|
||||
required: ["id", "title", "difficulty", "tags", "teaser", "solution"],
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -30,23 +29,24 @@ const RESPONSE_SCHEMA = {
|
||||
|
||||
function buildPrompt(count: number, avoidTitles: string[]): string {
|
||||
const avoidList = avoidTitles.length
|
||||
? `Evita repetir o parafrasear estos titulos ya usados: ${avoidTitles.join(", ")}.`
|
||||
? `Evita repetir o parafrasear estos títulos ya usados: ${avoidTitles.join(", ")}.`
|
||||
: "";
|
||||
|
||||
return `Sos un escritor experto en acertijos narrativos de pensamiento lateral, en el estilo del juego de mesa "historias negras"/"black stories": se cuenta un enigma breve y desconcertante (el "teaser"), y los jugadores deben adivinar la explicacion completa (la "solution") haciendo preguntas de si/no.
|
||||
return `Eres un escritor experto en acertijos narrativos de pensamiento lateral, al estilo del juego de mesa "historias negras"/"black stories": se cuenta un enigma breve y desconcertante (el "teaser"), y los jugadores deben adivinar la explicación completa (la "solution") haciendo preguntas de sí/no.
|
||||
|
||||
Genera exactamente ${count} historias completamente ORIGINALES en español (no copies acertijos clasicos ni de ningun juego comercial existente). Cada historia debe tener:
|
||||
- id: slug corto en minusculas separado por guiones, unico, derivado del titulo.
|
||||
- title: titulo corto y evocador.
|
||||
Genera exactamente ${count} historias completamente ORIGINALES en español (no copies acertijos clásicos ni de ningún juego comercial existente). Cada historia debe tener:
|
||||
- id: slug corto en minúsculas separado por guiones, único, derivado del título.
|
||||
- title: título corto y evocador.
|
||||
- difficulty: "easy", "medium" o "hard", variando entre las ${count} historias.
|
||||
- tags: 1 a 3 palabras clave en minusculas.
|
||||
- teaser: 2 a 4 frases. Presenta una situacion extraña o aparentemente inexplicable, resoluble con preguntas de si/no. No debe insinuar la solucion.
|
||||
- hints: entre 3 y 4 pistas progresivas (de mas vaga a mas reveladora) que el narrador puede leer si los jugadores estan trabados, sin regalar la solucion completa en las primeras.
|
||||
- solution: la explicacion completa y coherente que resuelve el enigma, respondiendo a todo lo planteado en el teaser. 4 a 8 frases.
|
||||
- tags: 1 a 3 palabras clave en minúsculas.
|
||||
- teaser: 2 a 4 frases. Presenta una situación extraña o aparentemente inexplicable, resoluble con preguntas de sí/no. No debe insinuar la solución.
|
||||
- solution: la explicación completa y coherente que resuelve el enigma, respondiendo a todo lo planteado en el teaser. 4 a 8 frases.
|
||||
|
||||
Las historias deben ser aptas para todo publico (sin violencia grafica extrema, sin contenido sexual), pueden ser misteriosas, agridulces o con un giro emotivo, pero siempre con una explicacion logica y satisfactoria. ${avoidList}
|
||||
Las historias deben ser aptas para todo público (sin violencia gráfica extrema, sin contenido sexual), pueden ser misteriosas, agridulces o con un giro emotivo, pero siempre con una explicación lógica y satisfactoria. ${avoidList}
|
||||
|
||||
Devolve unicamente el JSON que respeta el schema indicado.`;
|
||||
Importante sobre el idioma: todo el texto de cada historia (title, teaser, solution y tags) debe estar escrito en castellano de España (español peninsular), con su vocabulario, expresiones y gramática característicos (por ejemplo "vosotros", "coger", "ordenador"). No uses español latinoamericano ni ninguna otra variante regional del español.
|
||||
|
||||
Devuelve únicamente el JSON que respeta el schema indicado.`;
|
||||
}
|
||||
|
||||
interface GeminiResponse {
|
||||
@@ -60,7 +60,7 @@ export async function generateStoriesWithGemini(
|
||||
avoidTitles: string[] = []
|
||||
): Promise<Story[]> {
|
||||
if (!config.geminiApiKey) {
|
||||
throw new Error("GEMINI_API_KEY no esta configurada");
|
||||
throw new Error("GEMINI_API_KEY is not configured");
|
||||
}
|
||||
|
||||
const body = {
|
||||
@@ -86,13 +86,13 @@ export async function generateStoriesWithGemini(
|
||||
const data = (await res.json()) as GeminiResponse;
|
||||
const text = data.candidates?.[0]?.content?.parts?.[0]?.text;
|
||||
if (!text) {
|
||||
throw new Error("Respuesta de Gemini sin contenido de texto");
|
||||
throw new Error("Gemini response has no text content");
|
||||
}
|
||||
|
||||
const parsedJson = JSON.parse(text);
|
||||
const validated = GeminiStoryBatchSchema.parse(parsedJson);
|
||||
|
||||
// Aseguramos ids unicos por si el modelo repite alguno.
|
||||
// Ensure unique ids in case the model repeats one.
|
||||
const seen = new Set<string>();
|
||||
for (const story of validated.stories) {
|
||||
let id = story.id;
|
||||
|
||||
@@ -15,5 +15,5 @@ app.get("/api/health", (_req, res) => {
|
||||
app.use("/api", storiesRouter);
|
||||
|
||||
app.listen(config.port, () => {
|
||||
console.log(`API de historias escuchando en http://localhost:${config.port}`);
|
||||
console.log(`Stories API listening on http://localhost:${config.port}`);
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { promises as fs } from "node:fs";
|
||||
|
||||
/** Atomic write: writes to a temp file and then renames it. */
|
||||
export async function writeJsonAtomic(filePath: string, data: unknown): Promise<void> {
|
||||
const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
||||
await fs.writeFile(tmpPath, JSON.stringify(data, null, 2), "utf8");
|
||||
await fs.rename(tmpPath, filePath);
|
||||
}
|
||||
|
||||
export function isNodeError(err: unknown): err is NodeJS.ErrnoException {
|
||||
return typeof err === "object" && err !== null && "code" in err;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const RatingInputSchema = z.object({
|
||||
rating: z.number().int().min(1).max(5),
|
||||
});
|
||||
|
||||
export const RatingEntrySchema = z.object({
|
||||
storyId: z.string().min(1),
|
||||
rating: z.number().int().min(1).max(5),
|
||||
ratedAt: z.string(),
|
||||
});
|
||||
export type RatingEntry = z.infer<typeof RatingEntrySchema>;
|
||||
@@ -0,0 +1,32 @@
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { config } from "./config.js";
|
||||
import { ensureDataDir } from "./storyStore.js";
|
||||
import { isNodeError, writeJsonAtomic } from "./lib/jsonFile.js";
|
||||
import { RatingEntrySchema, type RatingEntry } from "./ratingSchema.js";
|
||||
|
||||
const RATINGS_FILE = "ratings.json";
|
||||
|
||||
function ratingsPath(): string {
|
||||
return path.join(config.dataDir, RATINGS_FILE);
|
||||
}
|
||||
|
||||
/** Returns every rating ever submitted by players (empty array if none yet). */
|
||||
export async function readRatings(): Promise<RatingEntry[]> {
|
||||
try {
|
||||
const raw = await fs.readFile(ratingsPath(), "utf8");
|
||||
const parsed = JSON.parse(raw);
|
||||
return RatingEntrySchema.array().parse(parsed);
|
||||
} catch (err: unknown) {
|
||||
if (isNodeError(err) && err.code === "ENOENT") return [];
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Appends one player-submitted difficulty rating (1-5) for a story. */
|
||||
export async function addRating(storyId: string, rating: number): Promise<void> {
|
||||
await ensureDataDir();
|
||||
const existing = await readRatings();
|
||||
existing.push({ storyId, rating, ratedAt: new Date().toISOString() });
|
||||
await writeJsonAtomic(ratingsPath(), existing);
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import { Router } from "express";
|
||||
import { config } from "../config.js";
|
||||
import { generateStoriesWithGemini } from "../gemini.js";
|
||||
import { addRating } from "../ratingStore.js";
|
||||
import { RatingInputSchema } from "../ratingSchema.js";
|
||||
import { getLatestStories, saveDailyStories } from "../storyStore.js";
|
||||
|
||||
export const storiesRouter = Router();
|
||||
|
||||
/** GET /api/stories: devuelve el ultimo lote generado, o 204 si no hay ninguno todavia. */
|
||||
/** GET /api/stories: returns the latest generated batch, or 204 if none exists yet. */
|
||||
storiesRouter.get("/stories", async (_req, res) => {
|
||||
const latest = await getLatestStories();
|
||||
if (!latest) {
|
||||
@@ -17,15 +19,33 @@ storiesRouter.get("/stories", async (_req, res) => {
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/admin/generate: dispara manualmente una generacion con Gemini.
|
||||
* Requiere header "x-admin-token" que coincida con ADMIN_TOKEN.
|
||||
* Pensado para pruebas manuales; la generacion diaria real la dispara el
|
||||
* systemd timer llamando al script generateDaily.
|
||||
* POST /api/stories/:id/ratings: records a player's voluntary 1-5 difficulty
|
||||
* rating for a story once the round is over. Open endpoint, no auth — this
|
||||
* is a low-stakes, best-effort signal used later by the reclassification
|
||||
* script, not a security-sensitive write. Works for any story id, including
|
||||
* ones from the default set embedded in the frontend (the backend doesn't
|
||||
* need to know a story to accept a rating for it).
|
||||
*/
|
||||
storiesRouter.post("/stories/:id/ratings", async (req, res) => {
|
||||
const parsed = RatingInputSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: "invalid rating" });
|
||||
return;
|
||||
}
|
||||
await addRating(req.params.id, parsed.data.rating);
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/admin/generate: manually triggers a generation run with Gemini.
|
||||
* Requires an "x-admin-token" header matching ADMIN_TOKEN.
|
||||
* Meant for manual testing; the real daily generation is triggered by the
|
||||
* systemd timer calling the generateDaily script.
|
||||
*/
|
||||
storiesRouter.post("/admin/generate", async (req, res) => {
|
||||
const token = req.header("x-admin-token");
|
||||
if (!token || token !== config.adminToken) {
|
||||
res.status(401).json({ error: "token invalido" });
|
||||
res.status(401).json({ error: "invalid token" });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -36,7 +56,7 @@ storiesRouter.post("/admin/generate", async (req, res) => {
|
||||
const saved = await saveDailyStories(stories);
|
||||
res.json(saved);
|
||||
} catch (err) {
|
||||
console.error("Error generando historias:", err);
|
||||
res.status(500).json({ error: "fallo la generacion", detail: String(err) });
|
||||
console.error("Error generating stories:", err);
|
||||
res.status(500).json({ error: "generation failed", detail: String(err) });
|
||||
}
|
||||
});
|
||||
@@ -1,17 +1,17 @@
|
||||
/**
|
||||
* Script pensado para correr una vez al dia via systemd timer / cron.
|
||||
* Genera STORIES_PER_DAY historias nuevas con Gemini y las guarda como el
|
||||
* nuevo "latest.json" que sirve la API.
|
||||
* Script meant to run once a day via a systemd timer / cron.
|
||||
* Generates STORIES_PER_DAY new stories with Gemini and saves them as the
|
||||
* new "latest.json" served by the API.
|
||||
*
|
||||
* Uso: npm run generate (dev, con tsx)
|
||||
* npm run generate:built (prod, tras "npm run build")
|
||||
* Usage: npm run generate (dev, with tsx)
|
||||
* npm run generate:built (prod, after "npm run build")
|
||||
*/
|
||||
import { config } from "../config.js";
|
||||
import { generateStoriesWithGemini } from "../gemini.js";
|
||||
import { getLatestStories, saveDailyStories } from "../storyStore.js";
|
||||
|
||||
async function main() {
|
||||
console.log(`[${new Date().toISOString()}] Generando ${config.storiesPerDay} historias nuevas con ${config.geminiModel}...`);
|
||||
console.log(`[${new Date().toISOString()}] Generating ${config.storiesPerDay} new stories with ${config.geminiModel}...`);
|
||||
|
||||
const previous = await getLatestStories();
|
||||
const avoidTitles = previous?.stories.map((s) => s.title) ?? [];
|
||||
@@ -19,11 +19,11 @@ async function main() {
|
||||
const stories = await generateStoriesWithGemini(config.storiesPerDay, avoidTitles);
|
||||
const saved = await saveDailyStories(stories);
|
||||
|
||||
console.log(`[${new Date().toISOString()}] OK: ${saved.stories.length} historias guardadas.`);
|
||||
console.log(`[${new Date().toISOString()}] OK: ${saved.stories.length} stories saved.`);
|
||||
for (const s of saved.stories) console.log(` - (${s.difficulty}) ${s.title}`);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Fallo la generacion diaria:", err);
|
||||
console.error("Daily generation failed:", err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Script meant to run periodically via a systemd timer / cron.
|
||||
* Aggregates player-submitted difficulty ratings (1-5) per story and, for
|
||||
* stories with enough ratings, updates their difficulty band in the
|
||||
* currently served batch (latest.json). Stories from the frontend's
|
||||
* embedded default set aren't affected since the backend has no way to
|
||||
* modify the client bundle.
|
||||
*
|
||||
* Usage: npm run reclassify (dev, with tsx)
|
||||
* npm run reclassify:built (prod, after "npm run build")
|
||||
*/
|
||||
import { config } from "../config.js";
|
||||
import { readRatings } from "../ratingStore.js";
|
||||
import type { Difficulty } from "../storySchema.js";
|
||||
import { getLatestStories, saveDailyStories } from "../storyStore.js";
|
||||
|
||||
/** Maps a 1-5 average rating to a difficulty band, splitting the scale into three equal thirds. */
|
||||
function difficultyFromAverage(average: number): Difficulty {
|
||||
if (average <= 2.33) return "easy";
|
||||
if (average <= 3.67) return "medium";
|
||||
return "hard";
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const ratings = await readRatings();
|
||||
if (ratings.length === 0) {
|
||||
console.log(`[${new Date().toISOString()}] No ratings collected yet, nothing to reclassify.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const byStory = new Map<string, number[]>();
|
||||
for (const entry of ratings) {
|
||||
const list = byStory.get(entry.storyId) ?? [];
|
||||
list.push(entry.rating);
|
||||
byStory.set(entry.storyId, list);
|
||||
}
|
||||
|
||||
const latest = await getLatestStories();
|
||||
if (!latest) {
|
||||
console.log(`[${new Date().toISOString()}] No generated story batch to reclassify (backend hasn't generated any yet).`);
|
||||
return;
|
||||
}
|
||||
|
||||
let changed = 0;
|
||||
const updatedStories = latest.stories.map((story) => {
|
||||
const votes = byStory.get(story.id);
|
||||
if (!votes || votes.length < config.minRatingsForReclassification) return story;
|
||||
|
||||
const average = votes.reduce((sum, v) => sum + v, 0) / votes.length;
|
||||
const newDifficulty = difficultyFromAverage(average);
|
||||
if (newDifficulty === story.difficulty) return story;
|
||||
|
||||
changed++;
|
||||
console.log(
|
||||
` - "${story.title}": ${story.difficulty} -> ${newDifficulty} (avg ${average.toFixed(2)} over ${votes.length} ratings)`
|
||||
);
|
||||
return { ...story, difficulty: newDifficulty };
|
||||
});
|
||||
|
||||
if (changed === 0) {
|
||||
console.log(`[${new Date().toISOString()}] Reviewed ${byStory.size} rated stories, no difficulty changes needed.`);
|
||||
return;
|
||||
}
|
||||
|
||||
await saveDailyStories(updatedStories);
|
||||
console.log(`[${new Date().toISOString()}] OK: reclassified ${changed} stor${changed === 1 ? "y" : "ies"}.`);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Difficulty reclassification failed:", err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const DifficultySchema = z.enum(["easy", "medium", "hard"]);
|
||||
export type Difficulty = z.infer<typeof DifficultySchema>;
|
||||
|
||||
export const StorySchema = z.object({
|
||||
id: z.string().min(1),
|
||||
@@ -8,7 +9,6 @@ export const StorySchema = z.object({
|
||||
difficulty: DifficultySchema,
|
||||
tags: z.array(z.string()).default([]),
|
||||
teaser: z.string().min(1),
|
||||
hints: z.array(z.string()).min(1).max(5),
|
||||
solution: z.string().min(1),
|
||||
});
|
||||
export type Story = z.infer<typeof StorySchema>;
|
||||
@@ -21,7 +21,7 @@ export const StoryListSchema = z.object({
|
||||
});
|
||||
export type StoryList = z.infer<typeof StoryListSchema>;
|
||||
|
||||
// Esquema que le pedimos a Gemini que respete (sin el wrapper de version/source).
|
||||
// Schema we ask Gemini to follow (without the version/source wrapper).
|
||||
export const GeminiStoryBatchSchema = z.object({
|
||||
stories: z.array(StorySchema).min(1),
|
||||
});
|
||||
@@ -1,11 +1,12 @@
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { config } from "./config.js";
|
||||
import { isNodeError, writeJsonAtomic } from "./lib/jsonFile.js";
|
||||
import { StoryListSchema, type Story, type StoryList } from "./storySchema.js";
|
||||
|
||||
const LATEST_FILE = "latest.json";
|
||||
|
||||
async function ensureDataDir(): Promise<void> {
|
||||
export async function ensureDataDir(): Promise<void> {
|
||||
await fs.mkdir(config.dataDir, { recursive: true });
|
||||
}
|
||||
|
||||
@@ -14,16 +15,9 @@ function dailyFileName(date: Date): string {
|
||||
return `${iso}.json`;
|
||||
}
|
||||
|
||||
/** Escritura atomica: escribe a un archivo temporal y luego renombra. */
|
||||
async function writeJsonAtomic(filePath: string, data: unknown): Promise<void> {
|
||||
const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
||||
await fs.writeFile(tmpPath, JSON.stringify(data, null, 2), "utf8");
|
||||
await fs.rename(tmpPath, filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Guarda un nuevo lote de historias generado hoy, tanto en un archivo fechado
|
||||
* (historial) como en latest.json (lo que sirve la API).
|
||||
* Saves a new batch of stories generated today, both in a dated file
|
||||
* (history) and in latest.json (what the API serves).
|
||||
*/
|
||||
export async function saveDailyStories(stories: Story[]): Promise<StoryList> {
|
||||
await ensureDataDir();
|
||||
@@ -45,9 +39,9 @@ export async function saveDailyStories(stories: Story[]): Promise<StoryList> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Devuelve el ultimo lote de historias generado (puede ser de un dia anterior
|
||||
* si la generacion de hoy todavia no corrio o fallo). Si nunca se genero
|
||||
* nada, devuelve null y el cliente debe usar su set default embebido.
|
||||
* Returns the latest generated batch of stories (may be from a previous day
|
||||
* if today's generation hasn't run yet or failed). If nothing has ever been
|
||||
* generated, returns null and the client should use its embedded default set.
|
||||
*/
|
||||
export async function getLatestStories(): Promise<StoryList | null> {
|
||||
const latestPath = path.join(config.dataDir, LATEST_FILE);
|
||||
@@ -60,7 +54,3 @@ export async function getLatestStories(): Promise<StoryList | null> {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function isNodeError(err: unknown): err is NodeJS.ErrnoException {
|
||||
return typeof err === "object" && err !== null && "code" in err;
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
# Ejemplo de virtual host para nginx en el LXC de Debian.
|
||||
# Sirve el frontend (build estatica de Vite) y reversa-proxea /api al backend
|
||||
# Node que corre en localhost:8787 via el servicio systemd story-api.
|
||||
# Example nginx virtual host for the Debian LXC.
|
||||
# Serves the frontend (static Vite build) and reverse-proxies /api to the
|
||||
# Node backend running on localhost:8787 via the story-api systemd service.
|
||||
#
|
||||
# Copialo a /etc/nginx/sites-available/historias, ajusta el dominio y la ruta,
|
||||
# y despues:
|
||||
# Copy it to /etc/nginx/sites-available/historias, adjust the domain and
|
||||
# path, then:
|
||||
# ln -s /etc/nginx/sites-available/historias /etc/nginx/sites-enabled/historias
|
||||
# nginx -t && systemctl reload nginx
|
||||
# Para TLS con Let's Encrypt: certbot --nginx -d tu-dominio.com
|
||||
# For TLS with Let's Encrypt: certbot --nginx -d your-domain.example
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name tu-dominio.com;
|
||||
server_name your-domain.example;
|
||||
|
||||
root /opt/historias/frontend/dist;
|
||||
index index.html;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[Unit]
|
||||
Description=API de Historias Incompletas
|
||||
Description=Sí, no, o indiferente API
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
@@ -11,7 +11,7 @@ EnvironmentFile=/opt/historias/backend/.env
|
||||
ExecStart=/usr/bin/node /opt/historias/backend/dist/index.js
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
# Endurecimiento basico del sandbox systemd
|
||||
# Basic systemd sandbox hardening
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[Unit]
|
||||
Description=Genera 5 historias nuevas del dia con Gemini
|
||||
Description=Generates 5 new stories for the day with Gemini
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[Unit]
|
||||
Description=Dispara la generacion diaria de historias (story-generate.service)
|
||||
Description=Triggers the daily story generation (story-generate.service)
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 06:00:00
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Reclassifies story difficulty from player ratings
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=historias
|
||||
Group=historias
|
||||
WorkingDirectory=/opt/historias/backend
|
||||
EnvironmentFile=/opt/historias/backend/.env
|
||||
ExecStart=/usr/bin/node /opt/historias/backend/dist/scripts/reclassifyDifficulty.js
|
||||
@@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Triggers the periodic difficulty reclassification (story-reclassify.service)
|
||||
|
||||
[Timer]
|
||||
OnCalendar=Sun *-*-* 05:00:00
|
||||
RandomizedDelaySec=600
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
Reference in new issue
Block a user