Compare commits

..

12 Commits

Author SHA1 Message Date
Madison Grubb
27dfed05ac improve image gen prompting. increase cfg from 1->3 to make prompt follow more aggressively
Some checks failed
ci/woodpecker/push/ci Pipeline failed
ci/woodpecker/cron/ci Pipeline was successful
2025-09-04 23:09:57 -04:00
Madison Grubb
714d0351ea fix png compression 2025-09-04 23:02:28 -04:00
Madison Grubb
f0e9ebccb9 cleanup console logs a little bit
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2025-09-04 22:59:37 -04:00
Madison Grubb
fad007ab1f increase encounter count by 3
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2025-09-04 22:54:52 -04:00
Madison Grubb
438943b032 cleanup template more for imagen
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2025-09-04 22:52:23 -04:00
Madison Grubb
50e240f314 fix name of file
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2025-09-04 22:48:57 -04:00
Madison Grubb
df08a6bf42 add png compression to save space
Some checks failed
ci/woodpecker/push/ci Pipeline failed
2025-09-04 22:48:11 -04:00
Madison Grubb
f51a5a6e0c shrink image more. improve prompts
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2025-09-04 22:38:03 -04:00
Madison Grubb
1e1bee6d05 add env var for comfyui in ci
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2025-09-04 22:18:14 -04:00
Madison Grubb
1e1d745e55 rework to allow for image gen
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
2025-09-04 16:52:13 -04:00
af315783e0 cleanup everything lol
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/cron/ci Pipeline was successful
2025-09-01 16:53:37 -04:00
15ce02eec1 revamp release uploads 2025-09-01 15:38:55 -04:00
12 changed files with 491 additions and 212 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
*.pdf *.pdf
*.png
.env .env
node_modules/** node_modules/**

View File

@@ -30,6 +30,8 @@ steps:
from_secret: OLLAMA_API_URL from_secret: OLLAMA_API_URL
OLLAMA_API_KEY: OLLAMA_API_KEY:
from_secret: OLLAMA_API_KEY from_secret: OLLAMA_API_KEY
COMFYUI_URL:
from_secret: COMFYUI_URL
commands: commands:
- npm ci - npm ci
- npm start - npm start
@@ -45,16 +47,32 @@ steps:
commands: commands:
- pdf=$(ls *.pdf | head -n1) - pdf=$(ls *.pdf | head -n1)
- tag=$(date +%F) - tag=$(date +%F)
# Create the release (ignore error if it already exists)
- | - |
curl -s -o /dev/null -w "%{http_code}" -X POST \ echo "Creating release for tag $tag..."
create_resp=$(curl -s -w "%{http_code}" -o /tmp/create.json -X POST \
-H "Authorization: token $GITEA_TOKEN" \ -H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-d "{\"tag_name\": \"$tag\", \"name\": \"$tag\", \"draft\": false, \"prerelease\": false}" \ -d "{\"tag_name\":\"$tag\",\"name\":\"$tag\"}" \
https://git.keligrubb.com/api/v1/repos/keligrubb/scrollsmith/releases || true https://git.keligrubb.com/api/v1/repos/keligrubb/scrollsmith/releases)
# Upload the PDF as a release asset echo "Create release HTTP status: $create_resp"
- | echo "Fetching release ID..."
curl -X POST \ release_id=$(curl -s \
-H "Authorization: token $GITEA_TOKEN" \
https://git.keligrubb.com/api/v1/repos/keligrubb/scrollsmith/releases/tags/$tag |
awk -F: '/"id"[ ]*:/ {gsub(/[^0-9]/,"",$2); print $2; exit}')
echo "Release ID = $release_id"
echo "Checking if asset $pdf already exists..."
assets=$(curl -s -H "Authorization: token $GITEA_TOKEN" \
https://git.keligrubb.com/api/v1/repos/keligrubb/scrollsmith/releases/$release_id/assets)
echo "Assets response: $assets"
if echo "$assets" | grep -q "\"name\":\"$pdf\""; then
echo "Asset $pdf already uploaded, skipping."
exit 0
fi
echo "Uploading $pdf to release $release_id..."
upload_resp=$(curl -s -w "%{http_code}" -o /tmp/upload.json -X POST \
-H "Authorization: token $GITEA_TOKEN" \ -H "Authorization: token $GITEA_TOKEN" \
-F "attachment=@$pdf" \ -F "attachment=@$pdf" \
"https://git.keligrubb.com/api/v1/repos/keligrubb/scrollsmith/releases/$tag/assets" https://git.keligrubb.com/api/v1/repos/keligrubb/scrollsmith/releases/$release_id/assets)
echo "Upload HTTP status: $upload_resp"
echo "Upload response: $(cat /tmp/upload.json)"

View File

@@ -22,12 +22,13 @@ Scrollsmith is a Node.js tool for generating Dungeons & Dragons one-page dungeon
- Node.js 22+ - Node.js 22+
- Ollama server running and accessible - Ollama server running and accessible
- Nextcloud (optional) for PDF uploads - Gitea Releases (optional) for PDF uploads
- `.env` file with: - `.env` file with:
```env ```env
OLLAMA_API_URL=http://localhost:3000/api/chat/completions OLLAMA_API_URL=http://localhost:3000/api/chat/completions
OLLAMA_API_KEY=your_api_key_here OLLAMA_API_KEY=your_api_key_here
COMFYUI_URL=http://192.168.1.124:8188
```` ````
--- ---
@@ -63,7 +64,7 @@ Optional: update the map path in `index.js` if you have a local dungeon map.
* Three-column layout: * Three-column layout:
* Column 1: Map, Adventure Hooks, Rumors * Column 1: Map, Adventure Hooks, Rumors
* Column 2: Keyed Rooms * Column 2: Rooms
* Column 3: Encounters, Treasure, NPCs * Column 3: Encounters, Treasure, NPCs
--- ---

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

View File

@@ -1,11 +1,6 @@
const OLLAMA_API_URL = process.env.OLLAMA_API_URL; import { callOllama } from "./ollamaClient.js";
const OLLAMA_API_KEY = process.env.OLLAMA_API_KEY;
async function sleep(ms) { // Utility: strip markdown artifacts
return new Promise(resolve => setTimeout(resolve, ms));
}
// --- Utility: strip markdown artifacts ---
function cleanText(str) { function cleanText(str) {
return str return str
.replace(/^#+\s*/gm, "") // remove headers .replace(/^#+\s*/gm, "") // remove headers
@@ -15,62 +10,17 @@ function cleanText(str) {
.trim(); .trim();
} }
async function callOllama(prompt, model = "gemma3n:e4b", retries = 5, stepName = "unknown") {
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const promptCharCount = prompt.length;
const promptWordCount = prompt.split(/\s+/).length;
console.log(`\n📤 [${stepName}] Sending prompt (attempt ${attempt}/${retries})`);
console.log(` Prompt: ${promptCharCount} chars, ~${promptWordCount} words`);
const response = await fetch(OLLAMA_API_URL, {
method: "POST",
headers: {
"Authorization": `Bearer ${OLLAMA_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model,
messages: [{ role: "user", content: prompt }],
}),
});
if (!response.ok) throw new Error(`Ollama request failed: ${response.status} ${response.statusText}`);
const data = await response.json();
const rawText = data.choices?.[0]?.message?.content;
if (!rawText) throw new Error("No response from Ollama");
const cleaned = cleanText(rawText);
console.log(`✅ [${stepName}] Received: ${rawText.length} chars, ~${rawText.split(/\s+/).length} words`);
console.log(`--- Raw output ---\n${rawText}\n`);
console.log(`--- Cleaned output ---\n${cleaned}\n`);
return cleaned;
} catch (err) {
console.warn(`⚠️ [${stepName}] Attempt ${attempt} failed: ${err.message}`);
if (attempt === retries) throw err;
const delay = 1000 * Math.pow(2, attempt) + Math.random() * 500;
console.log(` Retrying in ${Math.round(delay / 1000)}s...`);
await sleep(delay);
}
}
}
function parseList(raw) { function parseList(raw) {
return raw return raw
.split(/\n|(?=\d+[).]\s)/g) .split(/\n?\d+[).]\s+/)
.map(line => cleanText(line.replace(/^\d+[).\s-]*/, ""))) .map(line => cleanText(line))
.filter(Boolean); .filter(Boolean);
} }
function parseObjects(raw, type = "rooms") { function parseObjects(raw, type = "rooms") {
return raw return raw
.split("\n") .split(/\n?\d+[).]\s+/)
.map(line => cleanText(line.replace(/^\d+[).\s-]*/, ""))) .map(entry => cleanText(entry))
.filter(Boolean) .filter(Boolean)
.map(entry => { .map(entry => {
const [name, ...descParts] = entry.split(/[-–—:]/); const [name, ...descParts] = entry.split(/[-–—:]/);
@@ -83,9 +33,9 @@ function parseObjects(raw, type = "rooms") {
} }
export async function generateDungeon() { export async function generateDungeon() {
console.log("🏗️ Starting compact dungeon generation with debug logs...\n"); console.log("Starting compact dungeon generation with debug logs...\n");
// --- Step 1: Titles --- // Step 1: Titles
const titles10Raw = await callOllama( const titles10Raw = await callOllama(
`Generate 10 short, punchy dungeon titles (max 5 words each), numbered as a plain text list. `Generate 10 short, punchy dungeon titles (max 5 words each), numbered as a plain text list.
Each title should come from a different style or theme. Make the set varied and evocative. For example: Each title should come from a different style or theme. Make the set varied and evocative. For example:
@@ -97,111 +47,119 @@ Each title should come from a different style or theme. Make the set varied and
- Weird fantasy: uncanny, surreal, unsettling - Weird fantasy: uncanny, surreal, unsettling
- Whimsical: fun, quirky, playful - Whimsical: fun, quirky, playful
Avoid repeating materials or adjectives. Do not include explanations, markdown, or preambles. Only the 10 numbered titles.`, Avoid repeating materials or adjectives. Do not include any titles with the words "Obsidian" or "Clockwork". Do not include explanations, markdown, or preambles. Do not include the style or theme in parenthesis. Only the 10 numbered titles.`,
undefined, 5, "Step 1: Titles" undefined, 5, "Step 1: Titles"
); );
const titles10 = parseList(titles10Raw, 30); const titles10 = parseList(titles10Raw, 30);
console.log("🔹 Parsed titles10:", titles10); console.log("Parsed titles10:", titles10);
// --- Step 2: Narrow to 5 --- // Step 2: Narrow to 5
const titles5Raw = await callOllama( const titles5Raw = await callOllama(
`Here are 10 dungeon titles: `Here are 10 dungeon titles:
${titles10.join("\n")} ${titles10.join("\n")}
Select the 3 most interesting titles from the above list and create 2 additional unique titles. Randomly select 3 of the titles from the above list and create 2 additional unique titles. Do not include any titles with the words "Obsidian" or "Clockwork".
Output exactly 5 titles as a numbered list, plain text only. No explanations.`, Output exactly 5 titles as a numbered list, plain text only. No explanations.`,
undefined, 5, "Step 2: Narrow Titles" undefined, 5, "Step 2: Narrow Titles"
); );
const titles5 = parseList(titles5Raw, 30); const titles5 = parseList(titles5Raw, 30);
console.log("🔹 Parsed titles5:", titles5); console.log("Parsed titles5:", titles5);
// --- Step 3: Final title --- // Step 3: Final title
const bestTitleRaw = await callOllama( const bestTitleRaw = await callOllama(
`From the following 5 dungeon titles, select the one that sounds the most fun to play. `From the following 5 dungeon titles, randomly select only one of them.
Output only the title, no explanation, no numbering, no extra text: Output only the title, no explanation, no numbering, no extra text:
${titles5.join("\n")}`, ${titles5.join("\n")}`,
undefined, 5, "Step 3: Final Title" undefined, 5, "Step 3: Final Title"
); );
const title = cleanText(bestTitleRaw.split("\n")[0]); const title = cleanText(bestTitleRaw.split("\n")[0]);
console.log("🔹 Selected title:", title); console.log("Selected title:", title);
// --- Step 4: Flavor text --- // Step 4: Flavor text
const flavorRaw = await callOllama( const flavorRaw = await callOllama(
`Write a single evocative paragraph describing the dungeon titled "${title}". `Write a single evocative paragraph describing the location titled "${title}".
Do not include hooks, NPCs, treasure, or instructions. Output plain text only, one paragraph.`, Do not include hooks, NPCs, treasure, or instructions. Do not use bullet points or em-dashes. Output plain text only, one paragraph. Maximum 4 sentences.`,
undefined, 5, "Step 4: Flavor" undefined, 5, "Step 4: Flavor"
); );
const flavor = flavorRaw; const flavor = flavorRaw;
console.log("🔹 Flavor text:", flavor); console.log("Flavor text:", flavor);
// --- Step 5: Hooks & Rumors --- // Step 5: Hooks & Rumors
const hooksRumorsRaw = await callOllama( const hooksRumorsRaw = await callOllama(
`Based only on this dungeon flavor: `Based only on this location's flavor:
${flavor} ${flavor}
Generate 3 adventure hooks (one sentence each) and 3 rumors (one sentence each). Generate 3 short adventure hooks or rumors (mix them naturally).
Output numbered lists only, plain text. Maximum 120 characters per item. No explanations or extra text. Output as a single numbered list, plain text only. Do not use em-dashes.
Format as: Maximum 2 sentences per item. No explanations or extra text.`,
Hooks:
1. ...
2. ...
3. ...
Rumors:
1. ...
2. ...
3. ...`
,
undefined, 5, "Step 5: Hooks & Rumors" undefined, 5, "Step 5: Hooks & Rumors"
); );
const [hooksSection, rumorsSection] = hooksRumorsRaw.split(/Rumors[:\n]/i); const hooksRumors = parseList(hooksRumorsRaw, 120);
const hooks = parseList(hooksSection.replace(/Hooks[:\n]*/i, ""), 120); console.log("Hooks & Rumors:", hooksRumors);
const rumors = parseList(rumorsSection || "", 120);
console.log("🔹 Hooks:", hooks);
console.log("🔹 Rumors:", rumors);
// --- Step 6: Rooms & Encounters --- // Step 6: Rooms & Encounters
const roomsEncountersRaw = await callOllama( const roomsEncountersRaw = await callOllama(
`Using the flavor, hooks, and rumors: `Using the flavor and these hooks/rumors:
Flavor: Flavor:
${flavor} ${flavor}
Hooks: Hooks & Rumors:
${hooks.join("\n")} ${hooksRumors.join("\n")}
Rumors: Generate 5 rooms (name + short description) and 6 encounters (name + details).
${rumors.join("\n")}
Generate 5 rooms (name + short description) and 3 encounters (name + details).
Output two numbered lists, labeled "Rooms:" and "Encounters:". Plain text only. No extra explanation.`, Output two numbered lists, labeled "Rooms:" and "Encounters:". Plain text only. No extra explanation.`,
undefined, 5, "Step 6: Rooms & Encounters" undefined, 5, "Step 6: Rooms & Encounters"
); );
const [roomsSection, encountersSection] = roomsEncountersRaw.split(/Encounters[:\n]/i); const [roomsSection, encountersSection] = roomsEncountersRaw.split(/Encounters[:\n]/i);
const rooms = parseObjects(roomsSection.replace(/Rooms[:\n]*/i, ""), "rooms", 120); const rooms = parseObjects(roomsSection.replace(/Rooms[:\n]*/i, ""), "rooms", 120);
const encounters = parseObjects(encountersSection || "", "encounters", 120); const encounters = parseObjects(encountersSection || "", "encounters", 120);
console.log("🔹 Rooms:", rooms); console.log("Rooms:", rooms);
console.log("🔹 Encounters:", encounters); console.log("Encounters:", encounters);
// --- Step 7: Treasure & NPCs --- // Step 7: Treasure & NPCs
const treasureNpcsRaw = await callOllama( const treasureNpcsRaw = await callOllama(
`Based only on these rooms and encounters: `Based only on these rooms and encounters:
${JSON.stringify({ rooms, encounters }, null, 2)} ${JSON.stringify({ rooms, encounters }, null, 2)}
Generate 3 treasures and 3 NPCs (name + trait, max 2 sentences each). Generate 3 treasures and 3 NPCs (name + trait, max 2 sentences each).
Each NPC has a proper name, not just a title.
Treasure should sometimes include a danger or side-effect.
Output numbered lists labeled "Treasure:" and "NPCs:". Plain text only, no extra text.`, Output numbered lists labeled "Treasure:" and "NPCs:". Plain text only, no extra text.`,
undefined, 5, "Step 7: Treasure & NPCs" undefined, 5, "Step 7: Treasure & NPCs"
); );
const [treasureSection, npcsSection] = treasureNpcsRaw.split(/NPCs[:\n]/i); const [treasureSection, npcsSection] = treasureNpcsRaw.split(/NPCs[:\n]/i);
const treasure = parseList(treasureSection.replace(/Treasure[:\n]*/i, ""), 120); const treasure = parseList(treasureSection.replace(/Treasures?[:\n]*/i, ""), 120);
const npcs = parseObjects(npcsSection || "", "npcs", 120); const npcs = parseObjects(npcsSection || "", "npcs", 120);
console.log("🔹 Treasure:", treasure); console.log("Treasure:", treasure);
console.log("🔹 NPCs:", npcs); console.log("NPCs:", npcs);
console.log("\n🎉 Dungeon generation complete!"); // Step 8: Plot Resolutions
return { title, flavor, map: "map.png", hooks, rumors, rooms, encounters, treasure, npcs }; const plotResolutionsRaw = await callOllama(
`Based on the following location's flavor and story hooks:
Flavor:
${flavor}
Hooks & Rumors:
${hooksRumors.join("\n")}
Major NPCs / Encounters:
${[...npcs.map(n => n.name), ...encounters.map(e => e.name)].join(", ")}
Suggest 3 possible, non-conflicting story climaxes or plot resolutions for adventurers exploring this location.
These are prompts and ideas for brainstorming the story's ending, not fixed outcomes. Give the players meaningful choices and agency.
Start each item with phrases like "The adventurers could" or "The PCs might" to emphasize their hypothetical nature.
Deepen the narrative texture and allow roleplay and tactical creativity.
Keep each item short (max 2 sentences). Output as a numbered list, plain text only.`,
undefined, 5, "Step 8: Plot Resolutions"
);
const plotResolutions = parseList(plotResolutionsRaw, 180);
console.log("Plot Resolutions:", plotResolutions);
console.log("\nDungeon generation complete!");
return { title, flavor, map: "map.png", hooksRumors, rooms, encounters, treasure, npcs, plotResolutions };
} }

View File

@@ -4,36 +4,31 @@ function pickRandom(arr) {
export function dungeonTemplate(data) { export function dungeonTemplate(data) {
const bodyFonts = [ const bodyFonts = [
"'Libre Baskerville', serif", "'Lora', serif",
"'Cardo', serif",
"'Merriweather', serif", "'Merriweather', serif",
"'Fraunces', serif", "'Libre Baskerville', serif",
"'Source Serif 4', serif", "'Source Serif 4', serif"
"'Lora', serif"
]; ];
const headingFonts = [ const headingFonts = [
"'Cinzel Decorative', cursive", "'Cinzel', serif",
"'MedievalSharp', cursive", "'MedievalSharp', serif",
"'Metamorphous', cursive", "'Cormorant Garamond', serif",
"'Playfair Display', serif", "'Playfair Display', serif"
"'Alegreya Sans SC', sans-serif"
]; ];
const tableFonts = [ const tableFonts = [
"'Alegreya Sans', sans-serif", "'Alegreya Sans', sans-serif",
"'Cabin', sans-serif", "'Cabin', sans-serif",
"'IBM Plex Sans', sans-serif", "'IBM Plex Sans', sans-serif",
"'Cormorant Garamond', serif", "'Cormorant Garamond', serif"
"'Special Elite', monospace"
]; ];
const quoteFonts = [ const quoteFonts = [
"'Walter Turncoat', cursive", "'Playfair Display', serif",
"'Uncial Antiqua', serif", "'Uncial Antiqua', serif",
"'Beth Ellen', cursive", "'Libre Baskerville', serif",
"'Pinyon Script', cursive", "'Merriweather', serif"
"'Dela Gothic One', sans-serif"
]; ];
const bodyFont = pickRandom(bodyFonts); const bodyFont = pickRandom(bodyFonts);
@@ -47,62 +42,85 @@ export function dungeonTemplate(data) {
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>${data.title}</title> <title>${data.title}</title>
<link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville&family=Lora&family=Cinzel+Decorative&family=MedievalSharp&family=Alegreya+Sans+SC&family=Alegreya+Sans&family=Cabin&family=Walter+Turncoat&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Cinzel+Decorative&family=MedievalSharp&family=Metamorphous&family=Playfair+Display&family=Alegreya+Sans&family=Cabin&family=IBM+Plex+Sans&family=Cormorant+Garamond&family=Lora&family=Merriweather&family=Libre+Baskerville&family=Source+Serif+4&family=Walter+Turncoat&family=Uncial+Antiqua&family=Beth+Ellen&family=Pinyon+Script&display=swap" rel="stylesheet">
<style> <style>
@page { size: A4 landscape; margin: 0; } @page { size: A4 landscape; margin: 0; }
body { body {
margin: 0; padding: 1cm; margin: 0; padding: 1.5cm;
background: #d6c5a3; background: #f5f5f5;
font-family: ${bodyFont}; font-family: ${bodyFont};
color: #2b2118; color: #1a1a1a;
font-size: 0.8em; font-size: 0.7em;
line-height: 1.3em; line-height: 1.25em;
} }
h1 { h1 {
font-family: ${headingFont}; font-family: ${headingFont};
text-align: center; text-align: center;
font-size: 2em; font-size: 2em;
margin: 0.2em 0 0.3em; margin: 0.2em 0 0.3em;
color: #3e1f0e; color: #1a1a1a;
border-bottom: 2px solid #3e1f0e; border-bottom: 2px solid #1a1a1a;
padding-bottom: 0.2em; padding-bottom: 0.2em;
letter-spacing: 0.1em;
} }
.flavor { .flavor {
text-align: center; text-align: center;
font-style: italic; font-style: italic;
font-family: ${quoteFont}; font-family: ${quoteFont};
margin: 0.4em 0 1em; margin: 0.4em 0 0.8em;
font-size: 0.95em; font-size: 0.9em;
} }
.columns { .columns {
display: grid; display: grid;
grid-template-columns: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr 1fr;
gap: 0.8cm; gap: 0.5cm;
align-items: start; align-items: start;
} }
.col { .col {
display: flex; flex-direction: column; display: flex; flex-direction: column;
gap: 0.4em; gap: 0.15em;
} }
h2 { h2 {
font-family: ${headingFont}; font-family: ${headingFont};
font-size: 1em; font-size: 1.0em;
margin: 0.3em 0 0.1em; margin: 0.3em 0 0.1em;
color: #3e1f0e; color: #1a1a1a;
border-bottom: 1px solid #3e1f0e; border-bottom: 1px solid #1a1a1a;
padding-bottom: 0.1em; padding-bottom: 0.1em;
text-transform: uppercase;
letter-spacing: 0.05em;
} }
.map img { max-width: 100%; border: 2px solid #3e1f0e; border-radius: 0.2cm; }
.room h3 { margin: 0.2em 0 0.05em; font-size: 0.95em; font-weight: bold; } .room h3 { margin: 0.2em 0 0.05em; font-size: 0.95em; font-weight: bold; }
.room p { text-align: justify; word-wrap: break-word; margin: 0.1em 0 0.3em; } .room p { text-align: justify; word-wrap: break-word; margin: 0.1em 0 0.3em; }
ul { padding-left: 1em; margin: 0.1em 0 0.4em; } ul { padding-left: 1em; margin: 0.1em 0 0.3em; }
li { margin-bottom: 0.2em; } li { margin-bottom: 0.2em; }
table { width: 100%; border-collapse: collapse; font-family: ${tableFont}; font-size: 0.8em; } table { width: 100%; border-collapse: collapse; font-family: ${tableFont}; font-size: 0.8em; }
th, td { border: 1px solid #3e1f0e; padding: 0.2em; text-align: left; vertical-align: top; } th, td { border: 1px solid #1a1a1a; padding: 0.2em; text-align: left; vertical-align: top; }
th { background: #d9c6a5; } th { background: #e0e0e0; }
table tr:hover { background: rgba(62,31,14,0.05); } table tr:hover { background: rgba(0, 0, 0, 0.05); }
.map-page {
page-break-before: always;
display: flex;
align-items: center;
justify-content: center;
padding: 1.5cm;
height: calc(100vh - 3cm);
box-sizing: border-box;
background: #f5f5f5;
}
.map-page img {
max-width: 100%;
max-height: 100%;
height: auto;
width: auto;
border-radius: 0.2cm;
object-fit: contain;
box-shadow:
0 0 20px 15px #f5f5f5 inset,
0 0 5px 2px rgba(0, 0, 0, 0.05);
}
footer { footer {
text-align: center; font-size: 0.7em; color: #5a4632; margin-top: 0.5em; font-style: italic; text-align: center; font-size: 0.65em; color: #555; margin-top: 0.5em; font-style: italic;
} }
</style> </style>
</head> </head>
@@ -112,18 +130,10 @@ export function dungeonTemplate(data) {
<div class="columns"> <div class="columns">
<div class="col"> <div class="col">
<h2>Map</h2> <h2>Adventure Hooks & Rumors</h2>
<div class="map"><img src="file://${data.map}" alt="Dungeon Map"></div> <ul>${data.hooksRumors.map(item => `<li>${item}</li>`).join("")}</ul>
<h2>Adventure Hooks</h2> <h2>Locations</h2>
<ul>${data.hooks.map(h => `<li>${h}</li>`).join("")}</ul>
<h2>Rumors</h2>
<ul>${data.rumors.map(r => `<li>${r}</li>`).join("")}</ul>
</div>
<div class="col">
<h2>Keyed Rooms</h2>
${data.rooms.map((room, i) => `<div class="room"><h3>${i + 1}. ${room.name}</h3><p>${room.description}</p></div>`).join("")} ${data.rooms.map((room, i) => `<div class="room"><h3>${i + 1}. ${room.name}</h3><p>${room.description}</p></div>`).join("")}
</div> </div>
@@ -135,12 +145,21 @@ export function dungeonTemplate(data) {
<h2>Treasure</h2> <h2>Treasure</h2>
<ul>${data.treasure.map(t => `<li>${t}</li>`).join("")}</ul> <ul>${data.treasure.map(t => `<li>${t}</li>`).join("")}</ul>
</div>
<div class="col">
<h2>NPCs</h2> <h2>NPCs</h2>
<ul>${data.npcs.map(n => `<li><b>${n.name}</b>: ${n.trait}</li>`).join("")}</ul> <ul>${data.npcs.map(n => `<li><b>${n.name}</b>: ${n.trait}</li>`).join("")}</ul>
<h2>Plot Resolutions</h2>
<ul>${data.plotResolutions.map(p => `<li>${p}</li>`).join("")}</ul>
</div> </div>
</div> </div>
<div class="map-page">
<img src="${data.map}" alt="Dungeon Map">
</div>
<footer>Generated with Scrollsmith • © ${new Date().getFullYear()}</footer> <footer>Generated with Scrollsmith • © ${new Date().getFullYear()}</footer>
</body> </body>
</html> </html>

View File

@@ -1,12 +1,20 @@
import puppeteer from "puppeteer"; import puppeteer from "puppeteer";
import { dungeonTemplate } from "./dungeonTemplate.js"; import { dungeonTemplate } from "./dungeonTemplate.js";
export async function generateDungeonPDF(data, outputPath = "dungeon.pdf") { import fs from 'fs/promises';
export async function generatePDF(data, outputPath = "dungeon.pdf") {
const browser = await puppeteer.launch({ const browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'] args: ['--no-sandbox', '--disable-setuid-sandbox']
}); });
const page = await browser.newPage(); const page = await browser.newPage();
// Convert image to base64
const imageBuffer = await fs.readFile(data.map);
const base64Image = `data:image/png;base64,${imageBuffer.toString("base64")}`;
data.map = base64Image;
const html = dungeonTemplate(data); const html = dungeonTemplate(data);
await page.setContent(html, { waitUntil: "networkidle0" }); await page.setContent(html, { waitUntil: "networkidle0" });

207
imageGenerator.js Normal file
View File

@@ -0,0 +1,207 @@
import path from "path";
import { mkdir, writeFile } from "fs/promises";
import { fileURLToPath } from "url";
import { callOllama } from "./ollamaClient.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const COMFYUI_URL = process.env.COMFYUI_URL || "http://localhost:8188";
// Drawing style prefix
const STYLE_PREFIX = `clean line art, minimalist sketch, concept art sketch, black and white line drawing, lots of white space, sparse shading, simple hatching, very low detail, subtle color accent`;
// 1. Generate engineered visual prompt
async function generateVisualPrompt(flavor) {
const rawPrompt = await callOllama(
`You are a prompt engineer specializing in visual prompts for AI image generation. Your goal is to translate fantasy flavor text into a sparse, minimalist scene description.
Your output must be a simple list of visual tags describing only the most essential elements of the scene. Focus on the core subject and mood.
Rules:
- Describe a sparse scene with a single focal point or area.
- Use only 3-5 key descriptive phrases or tags.
- The entire output should be very short, 20-50 words maximum.
- Do NOT repeat wording from the input.
- Focus only on visual content, not style, medium, or camera effects.
- Avoid describing fine details; focus on large forms and the overall impression.
- Do NOT include phrases like “an image of” or “a scene showing”.
Input:
${flavor}
Output:`,
"gemma3n:e4b", 3, "Generate Visual Prompt"
);
return `${STYLE_PREFIX}, ${rawPrompt.trim().replace(/\n/g, " ")}`;
}
// 2. Save image buffer
async function saveImage(buffer, filename) {
const filepath = path.join(__dirname, filename);
await mkdir(__dirname, { recursive: true });
await writeFile(filepath, buffer);
console.log(`Saved image: ${filepath}`);
return filepath;
}
// 3. Build workflow payload
function buildComfyWorkflow(promptText, negativeText = "") {
return {
"3": {
"inputs": {
"seed": Math.floor(Math.random() * 100000),
"steps": 4,
"cfg": 3,
"sampler_name": "euler",
"scheduler": "simple",
"denoise": 1,
"model": ["4", 0],
"positive": ["6", 0],
"negative": ["7", 0],
"latent_image": ["5", 0]
},
"class_type": "KSampler"
},
"4": {
"inputs": {
"unet_name": "flux1-schnell-fp8.safetensors",
"weight_dtype": "fp8_e4m3fn"
},
"class_type": "UNETLoader"
},
"5": {
"inputs": {
"width": 640,
"height": 448,
"batch_size": 1
},
"class_type": "EmptyLatentImage"
},
"6": {
"inputs": {
"text": promptText,
"clip": ["10", 0]
},
"class_type": "CLIPTextEncode"
},
"7": {
"inputs": {
"text": negativeText,
"clip": ["10", 0]
},
"class_type": "CLIPTextEncode"
},
"10": {
"inputs": {
"clip_name1": "clip_l.safetensors",
"clip_name2": "t5xxl_fp8_e4m3fn.safetensors",
"type": "flux"
},
"class_type": "DualCLIPLoader"
},
"11": {
"inputs": {
"vae_name": "ae.safetensors"
},
"class_type": "VAELoader"
},
"8": {
"inputs": {
"samples": ["3", 0],
"vae": ["11", 0]
},
"class_type": "VAEDecode"
},
"9": {
"inputs": {
"filename_prefix": "ComfyUI_Flux",
"images": ["8", 0]
},
"class_type": "SaveImage"
}
};
}
// 4a. Wait for ComfyUI to finish image generation
async function waitForImage(promptId, timeout = 900000) {
const start = Date.now();
while (Date.now() - start < timeout) {
const res = await fetch(`${COMFYUI_URL}/history`);
const data = await res.json();
const historyEntry = data[promptId];
if (historyEntry?.outputs) {
const images = Object.values(historyEntry.outputs).flatMap(o => o.images || []);
if (images.length > 0) return images.map(i => i.filename);
}
await new Promise(resolve => setTimeout(resolve, 1000));
}
throw new Error("Timed out waiting for ComfyUI image result.");
}
// 4b. Download image from ComfyUI server
async function downloadImage(filename, localFilename) {
const url = `${COMFYUI_URL}/view?filename=${filename}`;
const res = await fetch(url);
if (!res.ok) throw new Error(`Failed to fetch image: ${res.statusText}`);
const buffer = Buffer.from(await res.arrayBuffer());
return await saveImage(buffer, localFilename);
}
// 4c. Submit prompt and handle full image pipeline
async function generateImageViaComfyUI(prompt, filename) {
const negativePrompt = `heavy shading, deep blacks, cross-hatching, dark, gritty, shadow-filled, chiaroscuro, scratchy lines, photorealism, hyper-realistic, high detail, 3D render, CGI, polished, smooth shading, detailed textures, noisy, cluttered, blurry, text, logo, signature, watermark`;
const workflow = buildComfyWorkflow(prompt, negativePrompt);
try {
console.log("Submitting prompt to ComfyUI...");
const res = await fetch(`${COMFYUI_URL}/prompt`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt: workflow })
});
if (!res.ok) {
throw new Error(`ComfyUI error: ${res.statusText}`);
}
const { prompt_id } = await res.json();
console.log("Waiting for image result...");
const filenames = await waitForImage(prompt_id);
if (filenames.length === 0) throw new Error("No image generated");
const comfyFilename = filenames[0];
console.log("Downloading image...");
const filepath = await downloadImage(comfyFilename, filename);
return filepath;
} catch (err) {
console.error("Error generating image:", err.message);
return null;
}
}
// 5. Main export
export async function generateDungeonImages({ flavor }) {
console.log("Generating dungeon image...");
const finalPrompt = await generateVisualPrompt(flavor);
console.log("Engineered visual prompt:\n", finalPrompt);
const filename = `dungeon.png`;
const filepath = await generateImageViaComfyUI(finalPrompt, filename);
if (!filepath) {
throw new Error("Failed to generate dungeon image.");
}
return filepath;
}

View File

@@ -1,6 +1,7 @@
import 'dotenv/config'; import 'dotenv/config';
import { generateDungeonPDF } from "./generateDungeon.js";
import { generateDungeon } from "./dungeonGenerator.js"; import { generateDungeon } from "./dungeonGenerator.js";
import { generateDungeonImages } from "./imageGenerator.js";
import { generatePDF } from "./generatePDF.js";
// Utility to create a filesystem-safe filename from the dungeon title // Utility to create a filesystem-safe filename from the dungeon title
function slugify(text) { function slugify(text) {
@@ -12,17 +13,19 @@ function slugify(text) {
(async () => { (async () => {
try { try {
// Generate dungeon JSON from Ollama // Generate the dungeon data
const dungeonData = await generateDungeon(); const dungeonData = await generateDungeon();
// Optional: replace the map placeholder with your local map path // Generate dungeon map image (uses dungeonData.flavor)
// dungeonData.map = "/absolute/path/to/dungeon-map.png"; const mapPath = await generateDungeonImages(dungeonData);
// Generate a safe filename based on the dungeon's title dungeonData.map = mapPath;
// Generate PDF filename based on the title
const filename = `${slugify(dungeonData.title)}.pdf`; const filename = `${slugify(dungeonData.title)}.pdf`;
// Generate PDF // Generate the PDF using full dungeon data (including map)
await generateDungeonPDF(dungeonData, filename); await generatePDF(dungeonData, filename);
console.log(`Dungeon PDF successfully generated: ${filename}`); console.log(`Dungeon PDF successfully generated: ${filename}`);
} catch (err) { } catch (err) {

78
ollamaClient.js Normal file
View File

@@ -0,0 +1,78 @@
const OLLAMA_API_URL = process.env.OLLAMA_API_URL;
const OLLAMA_API_KEY = process.env.OLLAMA_API_KEY;
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Utility: strip markdown artifacts
function cleanText(str) {
return str
.replace(/^#+\s*/gm, "") // remove headers
.replace(/\*\*(.*?)\*\*/g, "$1") // remove bold
.replace(/[*_`]/g, "") // remove stray formatting
.replace(/\s+/g, " ") // normalize whitespace
.trim();
}
export async function callOllama(prompt, model = "gemma3n:e4b", retries = 5, stepName = "unknown") {
const isUsingOpenWebUI = !!OLLAMA_API_KEY;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const promptCharCount = prompt.length;
const promptWordCount = prompt.split(/\s+/).length;
console.log(`\n[${stepName}] Sending prompt (attempt ${attempt}/${retries})`);
console.log(`Prompt: ${promptCharCount} chars, ~${promptWordCount} words`);
const headers = { "Content-Type": "application/json" };
if (isUsingOpenWebUI) {
headers["Authorization"] = `Bearer ${OLLAMA_API_KEY}`;
}
const body = isUsingOpenWebUI
? {
model,
messages: [{ role: "user", content: prompt }],
}
: {
model,
messages: [{ role: "user", content: prompt }],
stream: false,
};
const response = await fetch(OLLAMA_API_URL, {
method: "POST",
headers,
body: JSON.stringify(body),
});
if (!response.ok) throw new Error(`Ollama request failed: ${response.status} ${response.statusText}`);
const data = await response.json();
const rawText = isUsingOpenWebUI
? data.choices?.[0]?.message?.content
: data.message?.content;
if (!rawText) throw new Error("No response from Ollama");
const cleaned = cleanText(rawText);
console.log(`[${stepName}] Received: ${rawText.length} chars, ~${rawText.split(/\s+/).length} words`);
console.log(`Raw output:\n${rawText}\n`);
console.log(`Cleaned output:\n${cleaned}\n`);
return cleaned;
} catch (err) {
console.warn(`[${stepName}] Attempt ${attempt} failed: ${err.message}`);
if (attempt === retries) throw err;
const delay = 1000 * Math.pow(2, attempt) + Math.random() * 500;
console.log(`Retrying in ${Math.round(delay / 1000)}s...`);
await sleep(delay);
}
}
}

58
package-lock.json generated
View File

@@ -1,11 +1,11 @@
{ {
"name": "auto-dm", "name": "scrollsmith",
"version": "1.0.0", "version": "1.0.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "auto-dm", "name": "scrollsmith",
"version": "1.0.0", "version": "1.0.0",
"license": "SEE LICENSE IN README.md", "license": "SEE LICENSE IN README.md",
"dependencies": { "dependencies": {
@@ -42,9 +42,9 @@
} }
}, },
"node_modules/@eslint-community/eslint-utils": { "node_modules/@eslint-community/eslint-utils": {
"version": "4.7.0", "version": "4.8.0",
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.7.0.tgz", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.8.0.tgz",
"integrity": "sha512-dyybb3AcajC7uha6CvhdVRJqaKyn7w2YKqKyAN37NKYgZT36w+iRb0Dymmc5qEJ549c/S31cMMSFd75bteCpCw==", "integrity": "sha512-MJQFqrZgcW0UNYLGOuQpey/oTN59vyWwplvCGZztn1cKz9agZPPYpJB7h2OMmuu7VLqkvEjN8feFZJmxNF9D+Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
@@ -206,33 +206,19 @@
} }
}, },
"node_modules/@humanfs/node": { "node_modules/@humanfs/node": {
"version": "0.16.6", "version": "0.16.7",
"resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.6.tgz", "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz",
"integrity": "sha512-YuI2ZHQL78Q5HbhDiBA1X4LmYdXCKCMQIfw0pw7piHJwyREFebJUvrQN4cMssyES6x+vfUbx1CIpaQUKYdQZOw==", "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==",
"dev": true, "dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@humanfs/core": "^0.19.1", "@humanfs/core": "^0.19.1",
"@humanwhocodes/retry": "^0.3.0" "@humanwhocodes/retry": "^0.4.0"
}, },
"engines": { "engines": {
"node": ">=18.18.0" "node": ">=18.18.0"
} }
}, },
"node_modules/@humanfs/node/node_modules/@humanwhocodes/retry": {
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.1.tgz",
"integrity": "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=18.18"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/nzakas"
}
},
"node_modules/@humanwhocodes/module-importer": { "node_modules/@humanwhocodes/module-importer": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",
@@ -434,9 +420,9 @@
"optional": true "optional": true
}, },
"node_modules/bare-fs": { "node_modules/bare-fs": {
"version": "4.2.1", "version": "4.2.3",
"resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.2.1.tgz", "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.2.3.tgz",
"integrity": "sha512-mELROzV0IhqilFgsl1gyp48pnZsaV9xhQapHLDsvn4d4ZTfbFhcghQezl7FTEDNBcGqLUnNI3lUlm6ecrLWdFA==", "integrity": "sha512-1aGs5pRVLToMQ79elP+7cc0u0s/wXAzfBv/7hDloT7WFggLqECCas5qqPky7WHCFdsBH5WDq6sD4fAoz5sJbtA==",
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"dependencies": { "dependencies": {
@@ -700,9 +686,9 @@
"license": "BSD-3-Clause" "license": "BSD-3-Clause"
}, },
"node_modules/dotenv": { "node_modules/dotenv": {
"version": "17.2.1", "version": "17.2.2",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.1.tgz", "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.2.tgz",
"integrity": "sha512-kQhDYKZecqnM0fCnzI5eIv5L4cAe/iRI+HqMbO/hbRdTAeXDG+M9FjipUxNfbARuEg4iHIbhnhs78BCHNbSxEQ==", "integrity": "sha512-Sf2LSQP+bOlhKWWyhFsn0UsfdK/kCWRv1iuA2gXAwt3dyNabr6QSj00I2V10pidqz69soatm9ZwZvpQMTIOd5Q==",
"license": "BSD-2-Clause", "license": "BSD-2-Clause",
"engines": { "engines": {
"node": ">=12" "node": ">=12"
@@ -1616,9 +1602,9 @@
} }
}, },
"node_modules/puppeteer": { "node_modules/puppeteer": {
"version": "24.17.1", "version": "24.18.0",
"resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-24.17.1.tgz", "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-24.18.0.tgz",
"integrity": "sha512-KIuX0w+0um4TUbm55yFl2WIsbgjya2BHIgW9ylTuhavtwjXCOM7lMo9oLR1jQnCxrFvm9h/Yeb+zfs4nlgntPg==", "integrity": "sha512-Ke8oL/87GhzKIM2Ag6Yj49t5xbGc4rspGIuSuFLFCQBtYzWqCSanvqoCu08WkI78rbqcwnHjxiTH6oDlYFrjrw==",
"hasInstallScript": true, "hasInstallScript": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
@@ -1626,7 +1612,7 @@
"chromium-bidi": "8.0.0", "chromium-bidi": "8.0.0",
"cosmiconfig": "^9.0.0", "cosmiconfig": "^9.0.0",
"devtools-protocol": "0.0.1475386", "devtools-protocol": "0.0.1475386",
"puppeteer-core": "24.17.1", "puppeteer-core": "24.18.0",
"typed-query-selector": "^2.12.0" "typed-query-selector": "^2.12.0"
}, },
"bin": { "bin": {
@@ -1637,9 +1623,9 @@
} }
}, },
"node_modules/puppeteer-core": { "node_modules/puppeteer-core": {
"version": "24.17.1", "version": "24.18.0",
"resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.17.1.tgz", "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.18.0.tgz",
"integrity": "sha512-Msh/kf9k1XFN0wuKiT4/npMmMWOT7kPBEUw01gWvRoKOOoz3It9TEmWjnt4Gl4eO+p73VMrvR+wfa0dm9rfxjw==", "integrity": "sha512-As0BvfXxek2MbV0m7iqBmQKFnfSrzSvTM4zGipjd4cL+9f2Ccgut6RvHlc8+qBieKHqCMFy9BSI4QyveoYXTug==",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@puppeteer/browsers": "2.10.8", "@puppeteer/browsers": "2.10.8",

View File

@@ -1,5 +1,5 @@
{ {
"name": "auto-dm", "name": "scrollsmith",
"version": "1.0.0", "version": "1.0.0",
"main": "index.js", "main": "index.js",
"type": "module", "type": "module",