Compare commits
2 Commits
2025-09-14
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 1059eced53 | |||
|
|
96480a351f |
10
.gitignore
vendored
10
.gitignore
vendored
@@ -2,3 +2,13 @@
|
||||
*.png
|
||||
.env
|
||||
node_modules/**
|
||||
|
||||
# macOS dotfiles
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
.env.example
|
||||
|
||||
@@ -30,6 +30,7 @@ steps:
|
||||
from_secret: OLLAMA_API_URL
|
||||
OLLAMA_API_KEY:
|
||||
from_secret: OLLAMA_API_KEY
|
||||
OLLAMA_MODEL: gemma3:4b
|
||||
COMFYUI_URL:
|
||||
from_secret: COMFYUI_URL
|
||||
commands:
|
||||
|
||||
25
README.md
25
README.md
@@ -29,7 +29,7 @@ Scrollsmith is a Node.js tool for generating Dungeons & Dragons one-page dungeon
|
||||
OLLAMA_API_URL=http://localhost:3000/api/chat/completions
|
||||
OLLAMA_API_KEY=your_api_key_here
|
||||
COMFYUI_URL=http://192.168.1.124:8188
|
||||
````
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -43,6 +43,27 @@ npm install
|
||||
|
||||
---
|
||||
|
||||
## API Configuration
|
||||
|
||||
The client automatically infers the API type from the endpoint URL, making it flexible for different deployment scenarios.
|
||||
|
||||
### Direct Ollama API
|
||||
For direct Ollama API calls, set:
|
||||
```env
|
||||
OLLAMA_API_URL=http://localhost:11434/api/generate
|
||||
```
|
||||
|
||||
### Open WebUI API
|
||||
For Open WebUI API calls, set:
|
||||
```env
|
||||
OLLAMA_API_URL=http://localhost:3000/api/chat/completions
|
||||
OLLAMA_API_KEY=your_open_webui_api_key
|
||||
```
|
||||
|
||||
> Note: The API type is automatically inferred from the endpoint URL. If the URL contains `/api/chat/completions`, it uses Open WebUI API. If it contains `/api/generate`, it uses direct Ollama API. No `OLLAMA_API_TYPE` environment variable is required.
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
1. Make sure your Ollama server is running and `.env` is configured.
|
||||
@@ -78,4 +99,4 @@ Optional: update the map path in `index.js` if you have a local dungeon map.
|
||||
|
||||
## License
|
||||
|
||||
PROPRIETARY
|
||||
PROPRIETARY
|
||||
@@ -19,19 +19,253 @@ function parseList(raw) {
|
||||
}
|
||||
|
||||
function parseObjects(raw, type = "rooms") {
|
||||
let cleanedRaw = raw.replace(/Intermediate Rooms:/i, "").replace(/Climax Room:/i, "").trim();
|
||||
return cleanedRaw
|
||||
.split(/\n?\d+[).]\s+/)
|
||||
.map(entry => cleanText(entry))
|
||||
.filter(Boolean)
|
||||
.map(entry => {
|
||||
const [name, ...descParts] = entry.split(/[-–—:]/);
|
||||
const desc = descParts.join(" ").trim();
|
||||
if (type === "rooms") return { name: name.trim(), description: desc };
|
||||
if (type === "encounters") return { name: name.trim(), details: desc };
|
||||
if (type === "npcs") return { name: name.trim(), trait: desc };
|
||||
return entry;
|
||||
const cleanedRaw = raw.replace(/Intermediate Rooms:/i, "").replace(/Climax Room:/i, "").trim();
|
||||
const mapper = (entry) => {
|
||||
const [name, ...descParts] = entry.split(/[-–—:]/);
|
||||
const desc = descParts.join(" ").trim();
|
||||
const obj = { name: name.trim() };
|
||||
if (type === "rooms") return { ...obj, description: desc };
|
||||
if (type === "encounters") return { ...obj, details: desc };
|
||||
if (type === "npcs") return { ...obj, trait: desc };
|
||||
if (type === "treasure") return { ...obj, description: desc };
|
||||
return entry;
|
||||
};
|
||||
return cleanedRaw.split(/\n?\d+[).]\s+/).map(cleanText).filter(Boolean).map(mapper);
|
||||
}
|
||||
|
||||
const parseEncounterText = (text, idx) => {
|
||||
const match = text.match(/^(\d+)\s+(.+?)(?::\s*(.+))?$/);
|
||||
if (match) {
|
||||
const [, , name, details] = match;
|
||||
return name && details ? { name: name.trim(), details: details.trim() } : null;
|
||||
}
|
||||
const colonSplit = text.split(/[:]/);
|
||||
if (colonSplit.length > 1) {
|
||||
return {
|
||||
name: colonSplit[0].replace(/^\d+\s+/, "").trim(),
|
||||
details: colonSplit.slice(1).join(":").trim()
|
||||
};
|
||||
}
|
||||
const nameMatch = text.match(/^\d+\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)/);
|
||||
if (nameMatch) {
|
||||
return {
|
||||
name: nameMatch[1],
|
||||
details: text.replace(/^\d+\s+[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\s*/, "").trim()
|
||||
};
|
||||
}
|
||||
return { name: `Encounter ${idx + 1}`, details: text.replace(/^\d+\s+/, "").trim() };
|
||||
};
|
||||
|
||||
const splitCombinedEncounters = (encounters) => {
|
||||
const shouldSplit = encounters.length === 1 && (encounters[0].name === "1" || encounters[0].details.match(/\d+\s+[A-Z]/));
|
||||
if (!shouldSplit) return encounters;
|
||||
console.warn("Encounters appear combined, attempting to split...");
|
||||
const combinedText = encounters[0].details || "";
|
||||
const split = combinedText.split(/(?=\d+\s+[A-Z][a-z])/).filter(Boolean);
|
||||
return (split.length > 1 || (split.length === 1 && combinedText.length > 100))
|
||||
? split.map(parseEncounterText).filter(e => e?.name && e?.details?.length > 10)
|
||||
: encounters;
|
||||
};
|
||||
|
||||
const splitCombinedNPCs = (npcs) => {
|
||||
const shouldSplit = npcs.length === 1 && npcs[0].trait?.length > 80;
|
||||
if (!shouldSplit) return npcs;
|
||||
console.warn("NPCs appear combined, attempting to split...");
|
||||
const split = npcs[0].trait.split(/(?=[A-Z][a-z]+\s+[A-Z][a-z]+\s*:)/).filter(Boolean);
|
||||
return split.length > 1
|
||||
? split.map(text => {
|
||||
const [name, ...traitParts] = text.split(/[:]/);
|
||||
return { name: name.trim(), trait: traitParts.join(":").trim() };
|
||||
}).filter(n => n.name && n.trait?.length > 10)
|
||||
: npcs;
|
||||
};
|
||||
|
||||
const parseTreasureText = (text, idx, splitTreasures) => {
|
||||
if (idx === splitTreasures.length - 1 && text.length < 40) {
|
||||
return { name: splitTreasures[idx - 1]?.split(/\s+/).slice(-2).join(" ") || `Treasure ${idx}`, description: text };
|
||||
}
|
||||
const dashSplit = text.split(/[—]/);
|
||||
if (dashSplit.length === 2) return { name: dashSplit[0].trim(), description: dashSplit[1].trim() };
|
||||
if (text.length < 30 && /^[A-Z]/.test(text)) return { name: text.trim(), description: "" };
|
||||
return null;
|
||||
};
|
||||
|
||||
const splitCombinedTreasures = (treasure) => {
|
||||
const shouldSplit = treasure.length === 1 && treasure[0].description?.length > 60;
|
||||
if (!shouldSplit) return treasure;
|
||||
console.warn("Treasures appear combined, attempting to split...");
|
||||
const split = treasure[0].description.split(/\s+—\s+/).filter(Boolean);
|
||||
if (split.length <= 1) return treasure;
|
||||
const parsed = split.map((text, idx) => parseTreasureText(text, idx, split)).filter(t => t?.name && t?.description);
|
||||
if (parsed.length > 0) return parsed;
|
||||
const nameDescPairs = treasure[0].description.match(/([A-Z][^—]+?)\s+—\s+([^—]+?)(?=\s+[A-Z][^—]+\s+—|$)/g);
|
||||
return nameDescPairs
|
||||
? nameDescPairs.map(pair => {
|
||||
const match = pair.match(/([^—]+)\s+—\s+(.+)/);
|
||||
return match ? { name: match[1].trim(), description: match[2].trim() } : null;
|
||||
}).filter(t => t)
|
||||
: treasure;
|
||||
};
|
||||
|
||||
function extractCanonicalNames(dungeonData) {
|
||||
const names = {
|
||||
npcs: [],
|
||||
rooms: [],
|
||||
factions: []
|
||||
};
|
||||
|
||||
// Extract NPC names
|
||||
if (dungeonData.npcs) {
|
||||
dungeonData.npcs.forEach(npc => {
|
||||
if (npc.name) names.npcs.push(npc.name.trim());
|
||||
});
|
||||
}
|
||||
|
||||
// Extract room names
|
||||
if (dungeonData.rooms) {
|
||||
dungeonData.rooms.forEach(room => {
|
||||
if (room.name) names.rooms.push(room.name.trim());
|
||||
});
|
||||
}
|
||||
|
||||
// Extract faction names from core concepts (if available)
|
||||
if (dungeonData.coreConcepts) {
|
||||
const factionMatch = dungeonData.coreConcepts.match(/Primary Faction[:\s]+([^\.]+)/i);
|
||||
if (factionMatch) {
|
||||
names.factions.push(factionMatch[1].trim());
|
||||
}
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
function validateNameConsistency(dungeonData) {
|
||||
const canonicalNames = extractCanonicalNames(dungeonData);
|
||||
const fixes = [];
|
||||
|
||||
// Fix NPC names in all text fields - ensure consistency across all references
|
||||
canonicalNames.npcs.forEach(canonicalName => {
|
||||
// Check and fix in flavor text
|
||||
if (dungeonData.flavor) {
|
||||
const original = dungeonData.flavor;
|
||||
// Use canonical name as the source of truth
|
||||
dungeonData.flavor = dungeonData.flavor.replace(new RegExp(canonicalName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), canonicalName);
|
||||
if (original !== dungeonData.flavor) {
|
||||
fixes.push(`Fixed NPC name in flavor text: ${canonicalName}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Check and fix in hooks
|
||||
if (dungeonData.hooksRumors) {
|
||||
dungeonData.hooksRumors = dungeonData.hooksRumors.map(hook => {
|
||||
const original = hook;
|
||||
const fixed = hook.replace(new RegExp(canonicalName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), canonicalName);
|
||||
if (original !== fixed) {
|
||||
fixes.push(`Fixed NPC name in hook: ${canonicalName}`);
|
||||
}
|
||||
return fixed;
|
||||
});
|
||||
}
|
||||
|
||||
// Check and fix in encounters
|
||||
if (dungeonData.encounters) {
|
||||
dungeonData.encounters.forEach(encounter => {
|
||||
if (encounter.details) {
|
||||
const original = encounter.details;
|
||||
encounter.details = encounter.details.replace(new RegExp(canonicalName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), canonicalName);
|
||||
if (original !== encounter.details) {
|
||||
fixes.push(`Fixed NPC name in encounter: ${canonicalName}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Check and fix in plot resolutions
|
||||
if (dungeonData.plotResolutions) {
|
||||
dungeonData.plotResolutions = dungeonData.plotResolutions.map(resolution => {
|
||||
const original = resolution;
|
||||
const fixed = resolution.replace(new RegExp(canonicalName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), canonicalName);
|
||||
if (original !== fixed) {
|
||||
fixes.push(`Fixed NPC name in plot resolution: ${canonicalName}`);
|
||||
}
|
||||
return fixed;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Fix room names in encounters and other text
|
||||
canonicalNames.rooms.forEach(canonicalRoom => {
|
||||
if (dungeonData.encounters) {
|
||||
dungeonData.encounters.forEach(encounter => {
|
||||
if (encounter.details) {
|
||||
const original = encounter.details;
|
||||
encounter.details = encounter.details.replace(new RegExp(canonicalRoom.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), canonicalRoom);
|
||||
if (original !== encounter.details) {
|
||||
fixes.push(`Fixed room name in encounter: ${canonicalRoom}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return fixes;
|
||||
}
|
||||
|
||||
function standardizeEncounterLocations(encounters, rooms) {
|
||||
if (!encounters || !rooms) return { encounters, fixes: [] };
|
||||
|
||||
const roomNames = rooms.map(r => r.name.trim());
|
||||
const fixes = [];
|
||||
const fixedEncounters = encounters.map(encounter => {
|
||||
if (!encounter.details) return encounter;
|
||||
|
||||
let details = encounter.details.trim();
|
||||
const original = details;
|
||||
|
||||
// Check if details start with a room name
|
||||
for (const roomName of roomNames) {
|
||||
// Check for room name at start (with or without colon)
|
||||
const roomNameRegex = new RegExp(`^${roomName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*:?\\s*`, 'i');
|
||||
if (roomNameRegex.test(details)) {
|
||||
// Already has location, ensure format is "Location: Description"
|
||||
if (!details.match(new RegExp(`^${roomName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}:`, 'i'))) {
|
||||
details = details.replace(roomNameRegex, `${roomName}: `);
|
||||
fixes.push(`Standardized location format for encounter: ${encounter.name}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (original !== details) {
|
||||
encounter.details = details;
|
||||
}
|
||||
|
||||
return encounter;
|
||||
});
|
||||
|
||||
return { encounters: fixedEncounters, fixes };
|
||||
}
|
||||
|
||||
function validateAndFixContent(dungeonData) {
|
||||
const allFixes = [];
|
||||
|
||||
// Validate name consistency
|
||||
const nameFixes = validateNameConsistency(dungeonData);
|
||||
allFixes.push(...nameFixes);
|
||||
|
||||
// Standardize encounter locations
|
||||
if (dungeonData.encounters && dungeonData.rooms) {
|
||||
const locationResult = standardizeEncounterLocations(dungeonData.encounters, dungeonData.rooms);
|
||||
dungeonData.encounters = locationResult.encounters;
|
||||
allFixes.push(...locationResult.fixes);
|
||||
}
|
||||
|
||||
if (allFixes.length > 0) {
|
||||
console.log("\n[Validation] Applied fixes:");
|
||||
allFixes.forEach(fix => console.log(` - ${fix}`));
|
||||
}
|
||||
|
||||
return dungeonData;
|
||||
}
|
||||
|
||||
export async function generateDungeon() {
|
||||
@@ -47,6 +281,7 @@ Each title should come from a different style or theme. Make the set varied and
|
||||
- Weird fantasy: uncanny, surreal, unsettling
|
||||
- Whimsical: fun, quirky, playful
|
||||
|
||||
CRITICAL: Ensure all spelling is correct. Double-check all words before outputting.
|
||||
Avoid repeating materials or adjectives. Absolutely do not use the words "Obsidian" or "Clockwork" in any title. Do not include explanations, markdown, or preambles. Do not include the style or theme in parenthesis. Only the 50 numbered titles.`,
|
||||
undefined, 5, "Step 1: Titles"
|
||||
);
|
||||
@@ -72,9 +307,11 @@ Example:
|
||||
const flavorHooksRaw = await callOllama(
|
||||
`Based on the title "${title}" and these core concepts:
|
||||
${coreConcepts}
|
||||
Write a single evocative paragraph describing the location. Maximum 2 sentences. Maximum 100 words. Then, generate 3 short adventure hooks or rumors.
|
||||
The hooks should reference the central conflict, faction, and dynamic element.
|
||||
Output two sections labeled "Description:" and "Hooks & Rumors:". Use a numbered list for the hooks. Plain text only. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`,
|
||||
Write a single evocative paragraph describing the location. Maximum 2 sentences. Maximum 100 words. Then, generate 4-5 short adventure hooks or rumors.
|
||||
The hooks should reference the central conflict, faction, and dynamic element. Hooks should suggest different approaches (stealth, diplomacy, force, exploration) and create anticipation.
|
||||
CRITICAL: Hooks must be concise to fit in a single column on a one-page dungeon layout. Each hook must be a maximum of 35 words.
|
||||
CRITICAL: Ensure all spelling is correct. Double-check all words, especially proper nouns and technical terms.
|
||||
Output two sections labeled "Description:" and "Hooks & Rumors:". Use a numbered list for the hooks. Plain text only. Do not use em-dashes (—) anywhere in the output. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`,
|
||||
undefined, 5, "Step 3: Flavor & Hooks"
|
||||
);
|
||||
const [flavorSection, hooksSection] = flavorHooksRaw.split(/Hooks & Rumors[:\n]/i);
|
||||
@@ -88,9 +325,26 @@ Output two sections labeled "Description:" and "Hooks & Rumors:". Use a numbered
|
||||
`Based on the title "${title}", description "${flavor}", and these core concepts:
|
||||
${coreConcepts}
|
||||
Generate two key rooms that define the dungeon's narrative arc.
|
||||
1. **Entrance Room:** Give it a name and a description that sets the tone and introduces the environmental hazard.
|
||||
2. **Climax Room:** Give it a name and a description that includes the primary faction and the central conflict.
|
||||
Output as two numbered items, plain text only. Do not use bolded headings. Do not include any intro or other text. Only the numbered list. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`,
|
||||
CRITICAL: These rooms need rich environmental and tactical details with multiple interaction possibilities.
|
||||
|
||||
1. Entrance Room: Give it a name (max 5 words) and a description (30-40 words) that includes:
|
||||
- Immediate observable features and environmental details (lighting, sounds, smells, textures, temperature, visibility)
|
||||
- Interactable elements that players can use (levers, objects, portals, mechanisms, environmental hazards)
|
||||
- Tactical considerations (cover, elevation, movement restrictions, line of sight)
|
||||
- Sets the tone and introduces the environmental hazard/dynamic element
|
||||
|
||||
2. Climax Room: Give it a name (max 5 words) and a description (35-45 words) that includes:
|
||||
- Connection to the primary faction and the central conflict
|
||||
- Rich environmental and tactical details
|
||||
- Multiple approach options or solutions
|
||||
- Tactical considerations and environmental factors that affect gameplay
|
||||
|
||||
EXACT FORMAT REQUIRED - each room on its own numbered line:
|
||||
1. Room Name: Description text here.
|
||||
2. Room Name: Description text here.
|
||||
|
||||
CRITICAL: Ensure all spelling is correct. Double-check all words before outputting.
|
||||
Output ONLY the two numbered items, one per line. Use colons (:) to separate room names from descriptions, not em-dashes. Do not use em-dashes (—) anywhere. Do not combine items. Do not use bolded headings. Do not include any intro or other text. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`,
|
||||
undefined, 5, "Step 4: Key Rooms"
|
||||
);
|
||||
const [entranceSection, climaxSection] = keyRoomsRaw.split(/\n?2[).] /); // Split on "2. " to separate the two rooms
|
||||
@@ -99,7 +353,7 @@ Output as two numbered items, plain text only. Do not use bolded headings. Do no
|
||||
console.log("Entrance Room:", entranceRoom);
|
||||
console.log("Climax Room:", climaxRoom);
|
||||
|
||||
// Step 5: Main Content (Locations, Encounters, NPCs, Treasures)
|
||||
// Step 5: Main Content (Locations, Encounters, NPCs, Treasures, Random Events)
|
||||
const mainContentRaw = await callOllama(
|
||||
`Based on the following dungeon elements and the need for narrative flow:
|
||||
Title: "${title}"
|
||||
@@ -109,38 +363,158 @@ ${coreConcepts}
|
||||
Entrance Room: ${JSON.stringify(entranceRoom)}
|
||||
Climax Room: ${JSON.stringify(climaxRoom)}
|
||||
|
||||
Generate the rest of the dungeon's content to fill the space between the entrance and the climax.
|
||||
- **Strictly 3 Locations:** Each with a name and a short description (max 20 words). The description must be a single sentence. It should contain an environmental feature, a puzzle, or an element that connects to the core concepts or the final room.
|
||||
- **Strictly 4 Encounters:** Name and details. At least two encounters must be directly tied to the primary faction.
|
||||
- **Strictly 3 NPCs:** Proper name and a trait. One NPC should be a member of the primary faction, one should be a potential ally, and one should be a rival.
|
||||
- **Strictly 3 Treasures:** Name and a description that includes a danger or side-effect. Each treasure should be thematically tied to a specific encounter or room.
|
||||
Output as four separate numbered lists. Label the lists as "Locations:", "Encounters:", "NPCs:", and "Treasures:". Do not use any bolding, preambles, or extra text. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`,
|
||||
Generate the rest of the dungeon's content to fill the space between the entrance and the climax. CRITICAL: All content must fit on a single one-page dungeon layout with three columns. Keep descriptions rich and evocative with tactical/environmental details.
|
||||
|
||||
- **Strictly 3 Locations (EXACTLY 3, no more, no less):** Each with a name (max 6 words) and a description (30-40 words). Each room must include:
|
||||
- Rich environmental features that affect gameplay (lighting, sounds, smells, textures, temperature, visibility)
|
||||
- Interactable elements that players can use (levers, objects, portals, mechanisms, environmental hazards)
|
||||
- Multiple approaches or solutions to challenges in the room
|
||||
- Tactical considerations (cover, elevation, movement restrictions, line of sight)
|
||||
- Hidden aspects discoverable through interaction or investigation
|
||||
Format as "Name: description" using colons, NOT em-dashes.
|
||||
|
||||
- **Strictly 6 Encounters:** Numbered 1-6 (for d6 rolling). Name (max 6 words) and details (90-120 words per encounter). Each encounter must:
|
||||
- Start with the room/location name followed by a colon, then the details (e.g., "Location Name: Details text")
|
||||
- The location name must match one of the actual room names from this dungeon
|
||||
- Include environmental hazards/opportunities (cover, elevation, traps, interactable objects, terrain features)
|
||||
- Include tactical considerations (positioning, line of sight, escape routes, bottlenecks, high ground)
|
||||
- Offer multiple resolution options (combat, negotiation, stealth, puzzle-solving, environmental manipulation, timing-based solutions)
|
||||
- Include consequences and outcomes tied to player choices
|
||||
- Integrate with the environmental dynamic element from core concepts
|
||||
- At least two encounters must be directly tied to the primary faction
|
||||
Format as "Name: Location Name: details" using colons, NOT em-dashes. CRITICAL: Always start encounter details with the location name and a colon.
|
||||
|
||||
- **Strictly 4-5 NPCs:** Proper name (max 4 words) and a description (60-80 words). Each NPC must include:
|
||||
- Clear motivation or goal
|
||||
- Relationship to primary faction
|
||||
- How they can help or hinder the party
|
||||
- Quirks or memorable traits
|
||||
- Multiple interaction possibilities (negotiation, intimidation, help, betrayal)
|
||||
- One NPC should be a key figure tied to the central conflict
|
||||
- One should be a member of the primary faction, one should be a potential ally, one should be a rival
|
||||
Format as "Name: description" using colons, NOT em-dashes.
|
||||
|
||||
- **Strictly 4-5 Treasures:** Name (max 5 words) and a description (40-50 words). Each treasure must:
|
||||
- Include a clear danger or side-effect
|
||||
- Be connected to a specific encounter, NPC, or room
|
||||
- Have story significance beyond just value
|
||||
- Have potential for creative use beyond obvious purpose
|
||||
- Some should be cursed, have activation requirements, or serve dual purposes
|
||||
Format as "Name — Description" using em-dash.
|
||||
|
||||
- **Strictly 1 Random Events Table:** A d6 table (exactly 6 entries) with random events/wandering encounters. Each entry should:
|
||||
- Provide interesting complications or opportunities (not just combat)
|
||||
- Tie to the core concepts and dynamic element
|
||||
- Add replayability and surprise
|
||||
Format as numbered 1-6 list under "Random Events:" label.
|
||||
|
||||
CRITICAL: Each item must be on its own numbered line. DO NOT combine multiple items into a single numbered entry.
|
||||
|
||||
EXACT FORMAT REQUIRED:
|
||||
Locations:
|
||||
1. Location Name: Description text.
|
||||
2. Location Name: Description text.
|
||||
3. Location Name: Description text.
|
||||
|
||||
Encounters:
|
||||
1. Encounter Name: Location Name: Details text.
|
||||
2. Encounter Name: Location Name: Details text.
|
||||
3. Encounter Name: Location Name: Details text.
|
||||
4. Encounter Name: Location Name: Details text.
|
||||
5. Encounter Name: Location Name: Details text.
|
||||
6. Encounter Name: Location Name: Details text.
|
||||
|
||||
NPCs:
|
||||
1. NPC Name: Description text.
|
||||
2. NPC Name: Description text.
|
||||
3. NPC Name: Description text.
|
||||
4. NPC Name: Description text.
|
||||
|
||||
Treasures:
|
||||
1. Treasure Name — Description text.
|
||||
2. Treasure Name — Description text.
|
||||
3. Treasure Name — Description text.
|
||||
4. Treasure Name — Description text.
|
||||
|
||||
Random Events:
|
||||
1. Event description.
|
||||
2. Event description.
|
||||
3. Event description.
|
||||
4. Event description.
|
||||
5. Event description.
|
||||
6. Event description.
|
||||
|
||||
CRITICAL: Ensure all spelling is correct. Double-check all words, especially proper nouns, character names, and location names. Verify consistency of names across all sections.
|
||||
Output as five separate numbered lists with these exact labels: "Locations:", "Encounters:", "NPCs:", "Treasures:", and "Random Events:". Each item must be on its own line starting with a number. Do not combine items. Do not use any bolding, preambles, or extra text. Do not use em-dashes (—) in encounters or NPCs, only use colons for those sections. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`,
|
||||
undefined, 5, "Step 5: Main Content"
|
||||
);
|
||||
const [intermediateRoomsSection, encountersSection, npcsSection, treasureSection] = mainContentRaw.split(/Encounters:|NPCs:|Treasures?:/i);
|
||||
const [intermediateRoomsSection, encountersSection, npcsSection, treasureSection, randomEventsSection] = mainContentRaw.split(/Encounters:|NPCs:|Treasures?:|Random Events:/i);
|
||||
const intermediateRooms = parseObjects(intermediateRoomsSection.replace(/Locations:/i, ""), "rooms");
|
||||
const rooms = [entranceRoom, ...intermediateRooms, climaxRoom];
|
||||
const encounters = parseObjects(encountersSection || "", "encounters");
|
||||
const npcs = parseObjects(npcsSection || "", "npcs");
|
||||
const treasure = parseList(treasureSection || "");
|
||||
// Limit to exactly 3 intermediate rooms to ensure total of 5 rooms (entrance + 3 intermediate + climax)
|
||||
const limitedIntermediateRooms = intermediateRooms.slice(0, 3);
|
||||
if (intermediateRooms.length > 3) {
|
||||
console.warn(`Expected exactly 3 intermediate locations but got ${intermediateRooms.length}, limiting to first 3`);
|
||||
}
|
||||
const rooms = [entranceRoom, ...limitedIntermediateRooms, climaxRoom];
|
||||
const encounters = splitCombinedEncounters(parseObjects(encountersSection || "", "encounters"));
|
||||
const npcs = splitCombinedNPCs(parseObjects(npcsSection || "", "npcs"));
|
||||
const treasure = splitCombinedTreasures(parseObjects(treasureSection || "", "treasure"));
|
||||
const randomEvents = parseList(randomEventsSection || "");
|
||||
|
||||
[[encounters, 6, 'encounters'], [npcs, 4, 'NPCs'], [treasure, 4, 'treasures'], [randomEvents, 6, 'random events']]
|
||||
.filter(([arr, expected]) => arr.length < expected && arr.length > 0)
|
||||
.forEach(([arr, expected, name]) => console.warn(`Expected at least ${expected} ${name} but got ${arr.length}`));
|
||||
console.log("Rooms:", rooms);
|
||||
console.log("Encounters:", encounters);
|
||||
console.log("NPCs:", npcs);
|
||||
console.log("Treasure:", treasure);
|
||||
console.log("Random Events:", randomEvents);
|
||||
|
||||
// Step 6: Player Choices and Consequences
|
||||
const npcNamesList = npcs.map(n => n.name).join(", ");
|
||||
const factionName = coreConcepts.match(/Primary Faction[:\s]+([^\.]+)/i)?.[1]?.trim() || "the primary faction";
|
||||
|
||||
const plotResolutionsRaw = await callOllama(
|
||||
`Based on all of the following elements, suggest 3 possible, non-conflicting story climaxes or plot resolutions for adventurers exploring this location. Each resolution must provide a meaningful choice with a tangible consequence, directly related to the Central Conflict, the Primary Faction, or the NPCs.
|
||||
`Based on all of the following elements, suggest 4-5 possible, non-conflicting story climaxes or plot resolutions for adventurers exploring this location. Each resolution must provide a meaningful choice with a tangible consequence, directly related to the Central Conflict, the Primary Faction, or the NPCs.
|
||||
|
||||
Dungeon Elements:
|
||||
${JSON.stringify({ title, flavor, hooksRumors, rooms, encounters, treasure, npcs, coreConcepts }, null, 2)}
|
||||
|
||||
Start each item with phrases like "The adventurers could" or "The PCs might". Deepen the narrative texture and allow for roleplay and tactical creativity. Keep each item short (max 2 sentences). Output as a numbered list, plain text only. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`,
|
||||
CRITICAL: This content must fit in a single column on a one-page dungeon layout. Keep descriptions meaningful but concise.
|
||||
Start each item with phrases like "The adventurers could" or "The adventurers might". Do not use "PCs" or "player characters" - always use "adventurers" instead.
|
||||
|
||||
IMPORTANT: When referencing NPCs, use these exact names with correct spelling: ${npcNamesList}. When referencing the faction, use: ${factionName}. Ensure all names are spelled consistently and correctly.
|
||||
CRITICAL: Double-check all spelling before outputting. Verify all proper nouns match exactly as provided above.
|
||||
|
||||
Each resolution should:
|
||||
- Offer meaningful choice with clear consequences
|
||||
- Integrate NPCs, faction dynamics, and player actions
|
||||
- Include failure states or unexpected outcomes as options
|
||||
- Reflect different approaches players might take
|
||||
Keep each item to 50-60 words (2-3 sentences). Output as a numbered list, plain text only. Do not use em-dashes (—) anywhere in the output. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`,
|
||||
undefined, 5, "Step 6: Plot Resolutions"
|
||||
);
|
||||
const plotResolutions = parseList(plotResolutionsRaw);
|
||||
console.log("Plot Resolutions:", plotResolutions);
|
||||
|
||||
// Step 7: Validation and Content Fixing
|
||||
console.log("\n[Validation] Running content validation and fixes...");
|
||||
const dungeonData = {
|
||||
title,
|
||||
flavor,
|
||||
map: "map.png",
|
||||
hooksRumors,
|
||||
rooms,
|
||||
encounters,
|
||||
treasure,
|
||||
npcs,
|
||||
plotResolutions,
|
||||
randomEvents,
|
||||
coreConcepts
|
||||
};
|
||||
|
||||
const validatedData = validateAndFixContent(dungeonData);
|
||||
|
||||
console.log("\nDungeon generation complete!");
|
||||
return { title, flavor, map: "map.png", hooksRumors, rooms, encounters, treasure, npcs, plotResolutions };
|
||||
return validatedData;
|
||||
}
|
||||
|
||||
@@ -37,6 +37,9 @@ export function dungeonTemplate(data) {
|
||||
const tableFont = pickRandom(tableFonts);
|
||||
const quoteFont = pickRandom(quoteFonts);
|
||||
|
||||
// Check if we have a map image to include
|
||||
const hasMap = data.map && typeof data.map === 'string' && data.map.startsWith('data:image/');
|
||||
|
||||
return `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
@@ -56,13 +59,13 @@ export function dungeonTemplate(data) {
|
||||
padding: 0;
|
||||
font-family: ${bodyFont};
|
||||
color: #1a1a1a;
|
||||
font-size: 0.7em;
|
||||
line-height: 1.25em;
|
||||
font-size: 0.65em;
|
||||
line-height: 1.2em;
|
||||
}
|
||||
.content-page {
|
||||
height: 100vh;
|
||||
box-sizing: border-box;
|
||||
padding: 1.5cm;
|
||||
padding: 1.2cm;
|
||||
page-break-after: always;
|
||||
overflow: hidden;
|
||||
break-inside: avoid;
|
||||
@@ -71,160 +74,263 @@ export function dungeonTemplate(data) {
|
||||
font-family: ${headingFont};
|
||||
text-align: center;
|
||||
text-transform: uppercase;
|
||||
font-size: 2em;
|
||||
margin: 0.2em 0 0.3em;
|
||||
font-size: 1.8em;
|
||||
margin: 0.15em 0 0.2em;
|
||||
color: #1a1a1a;
|
||||
border-bottom: 2px solid #1a1a1a;
|
||||
padding-bottom: 0.2em;
|
||||
padding-bottom: 0.15em;
|
||||
letter-spacing: 0.1em;
|
||||
}
|
||||
.flavor {
|
||||
text-align: center;
|
||||
font-style: italic;
|
||||
font-family: ${quoteFont};
|
||||
margin: 0.4em 0 0.8em;
|
||||
font-size: 0.9em;
|
||||
margin: 0.3em 0 0.6em;
|
||||
font-size: 0.85em;
|
||||
line-height: 1.2em;
|
||||
}
|
||||
.columns {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr 1fr;
|
||||
gap: 0.5cm;
|
||||
gap: 0.4cm;
|
||||
align-items: start;
|
||||
}
|
||||
.col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.15em;
|
||||
overflow-wrap: break-word;
|
||||
word-break: break-word;
|
||||
}
|
||||
.section-block {
|
||||
break-inside: avoid;
|
||||
page-break-inside: avoid;
|
||||
margin-bottom: 0.25em;
|
||||
}
|
||||
h2 {
|
||||
font-family: ${headingFont};
|
||||
font-size: 1.0em;
|
||||
margin: 0.3em 0 0.1em;
|
||||
font-size: 0.95em;
|
||||
margin: 0.2em 0 0.2em;
|
||||
color: #1a1a1a;
|
||||
border-bottom: 1px solid #1a1a1a;
|
||||
padding-bottom: 0.1em;
|
||||
padding-bottom: 0.08em;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
break-inside: avoid;
|
||||
page-break-inside: avoid;
|
||||
}
|
||||
.room {
|
||||
break-inside: avoid;
|
||||
page-break-inside: avoid;
|
||||
}
|
||||
.room h3 {
|
||||
margin: 0.2em 0 0.05em;
|
||||
font-size: 0.95em;
|
||||
margin: 0.15em 0 0.08em;
|
||||
font-size: 0.85em;
|
||||
font-weight: bold;
|
||||
color: #1a1a1a;
|
||||
}
|
||||
.room p {
|
||||
text-align: justify;
|
||||
word-wrap: break-word;
|
||||
margin: 0.1em 0 0.3em;
|
||||
margin: 0 0 0.35em;
|
||||
font-size: 0.8em;
|
||||
font-weight: normal;
|
||||
line-height: 1.25em;
|
||||
}
|
||||
ul {
|
||||
padding-left: 1em;
|
||||
margin: 0.1em 0 0.3em;
|
||||
.encounter, .npc, .treasure, .plot-resolution {
|
||||
margin: 0 0 0.3em;
|
||||
break-inside: avoid;
|
||||
page-break-inside: avoid;
|
||||
font-size: 0.8em;
|
||||
line-height: 1.25em;
|
||||
}
|
||||
li {
|
||||
margin-bottom: 0.2em;
|
||||
.random-events {
|
||||
margin: 0.2em 0;
|
||||
break-inside: avoid;
|
||||
page-break-inside: avoid;
|
||||
font-size: 0.8em;
|
||||
}
|
||||
.random-events table {
|
||||
margin-top: 0.15em;
|
||||
}
|
||||
.encounter strong, .npc strong, .treasure strong {
|
||||
font-weight: bold;
|
||||
}
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-family: ${tableFont};
|
||||
margin: 0.2em 0;
|
||||
font-size: 0.8em;
|
||||
}
|
||||
th,
|
||||
td {
|
||||
break-inside: avoid;
|
||||
page-break-inside: avoid;
|
||||
border: 1px solid #1a1a1a;
|
||||
padding: 0.2em;
|
||||
}
|
||||
table th {
|
||||
font-family: ${headingFont};
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #1a1a1a;
|
||||
padding: 0.15em 0.3em;
|
||||
font-size: 0.85em;
|
||||
text-transform: uppercase;
|
||||
font-weight: bold;
|
||||
}
|
||||
table td {
|
||||
padding: 0.2em 0.3em;
|
||||
vertical-align: top;
|
||||
line-height: 1.3em;
|
||||
border-bottom: 1px solid #1a1a1a;
|
||||
}
|
||||
th {
|
||||
background: #e0e0e0;
|
||||
table tr:last-child td {
|
||||
border-bottom: 1px solid #1a1a1a;
|
||||
}
|
||||
table tr:hover {
|
||||
background: rgba(0, 0, 0, 0.05);
|
||||
table td:first-child {
|
||||
font-weight: bold;
|
||||
width: 2em;
|
||||
text-align: center;
|
||||
border-right: 1px solid #1a1a1a;
|
||||
}
|
||||
.encounters-table td:nth-child(2) {
|
||||
font-weight: bold;
|
||||
width: 30%;
|
||||
padding-right: 0.5em;
|
||||
border-right: 1px solid #1a1a1a;
|
||||
}
|
||||
.encounters-table td:nth-child(3) {
|
||||
width: auto;
|
||||
}
|
||||
.map-page {
|
||||
height: 210mm;
|
||||
width: 297mm;
|
||||
box-sizing: border-box;
|
||||
padding: 1.5cm;
|
||||
position: relative;
|
||||
display: block;
|
||||
}
|
||||
.map-image-container {
|
||||
position: absolute;
|
||||
top: 1.5cm;
|
||||
left: 1.5cm;
|
||||
right: 1.5cm;
|
||||
bottom: 3cm;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
page-break-before: always;
|
||||
}
|
||||
.map-page img {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
.map-page footer {
|
||||
position: absolute;
|
||||
bottom: 1.5cm;
|
||||
left: 1.5cm;
|
||||
right: 1.5cm;
|
||||
.map-container {
|
||||
text-align: center;
|
||||
font-size: 0.65em;
|
||||
color: #555;
|
||||
font-style: italic;
|
||||
margin: 1em 0;
|
||||
}
|
||||
.map-container img {
|
||||
max-width: 100%;
|
||||
max-height: calc(100vh - 3cm);
|
||||
border: 1px solid #1a1a1a;
|
||||
}
|
||||
ul {
|
||||
margin: 0.2em 0;
|
||||
padding-left: 1.2em;
|
||||
}
|
||||
li {
|
||||
margin: 0.08em 0;
|
||||
font-size: 0.8em;
|
||||
line-height: 1.25em;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="content-page">
|
||||
<h1>${data.title}</h1>
|
||||
<p class="flavor">${data.flavor}</p>
|
||||
${data.flavor ? `<p class="flavor">${data.flavor}</p>` : ''}
|
||||
|
||||
<div class="columns">
|
||||
<div class="col">
|
||||
<h2>Adventure Hooks & Rumors</h2>
|
||||
<ul>${data.hooksRumors.map(item => `<li>${item}</li>`).join("")}</ul>
|
||||
<h2>Locations</h2>
|
||||
${data.rooms.map((room, i) => `<div class="room">
|
||||
<h3>${i + 1}. ${room.name}</h3>
|
||||
<p>${room.description}</p>
|
||||
</div>`).join("")}
|
||||
${data.hooksRumors && data.hooksRumors.length > 0 ? `
|
||||
<div class="section-block">
|
||||
<h2>Hooks & Rumors</h2>
|
||||
<ul>
|
||||
${data.hooksRumors.map(hook => `<li>${hook}</li>`).join('')}
|
||||
</ul>
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
${data.randomEvents && data.randomEvents.length > 0 ? `
|
||||
<div class="section-block random-events">
|
||||
<h2>Random Events (d6)</h2>
|
||||
<table>
|
||||
<tbody>
|
||||
${data.randomEvents.map((event, index) => `
|
||||
<tr>
|
||||
<td>${index + 1}</td>
|
||||
<td>${event}</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
${data.rooms && data.rooms.length > 0 ? `
|
||||
<div class="section-block">
|
||||
<h2>Locations</h2>
|
||||
${data.rooms.map(room => `
|
||||
<div class="room">
|
||||
<h3>${room.name}</h3>
|
||||
<p>${room.description}</p>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
|
||||
<div class="col">
|
||||
<h2>Encounters</h2>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Details</th>
|
||||
</tr>
|
||||
${data.encounters.map(e => `<tr>
|
||||
<td>${e.name}</td>
|
||||
<td>${e.details}</td>
|
||||
</tr>`).join("")}
|
||||
</table>
|
||||
<h2>Treasure</h2>
|
||||
<ul>${data.treasure.map(t => {
|
||||
const [name, ...descParts] = t.split(/[-–—:]/);
|
||||
const description = descParts.join(" ").trim();
|
||||
return `<li><b>${name.trim()}</b>: ${description}</li>`;
|
||||
}).join("")}</ul>
|
||||
${data.encounters && data.encounters.length > 0 ? `
|
||||
<div class="section-block">
|
||||
<h2>Encounters (d6)</h2>
|
||||
<table class="encounters-table">
|
||||
<tbody>
|
||||
${data.encounters.map((encounter, index) => `
|
||||
<tr>
|
||||
<td>${index + 1}</td>
|
||||
<td><strong>${encounter.name}</strong></td>
|
||||
<td>${encounter.details}</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
|
||||
<div class="col">
|
||||
<h2>NPCs</h2>
|
||||
<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>
|
||||
${data.treasure && data.treasure.length > 0 ? `
|
||||
<div class="section-block">
|
||||
<h2>Treasure</h2>
|
||||
${data.treasure.map(item => `
|
||||
<div class="treasure">
|
||||
${typeof item === 'object' && item.name ? `<strong>${item.name}</strong> — ${item.description}` : item}
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
${data.npcs && data.npcs.length > 0 ? `
|
||||
<div class="section-block">
|
||||
<h2>NPCs</h2>
|
||||
${data.npcs.map(npc => `
|
||||
<div class="npc">
|
||||
<strong>${npc.name}</strong>: ${npc.trait}
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
${data.plotResolutions && data.plotResolutions.length > 0 ? `
|
||||
<div class="section-block">
|
||||
<h2>Plot Resolutions</h2>
|
||||
${data.plotResolutions.map(resolution => `
|
||||
<div class="plot-resolution">
|
||||
${resolution}
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="map-page">
|
||||
<div class="map-image-container">
|
||||
<img src="${data.map}" alt="Dungeon Map">
|
||||
|
||||
${hasMap ? `
|
||||
<div class="content-page map-page">
|
||||
<div class="map-container">
|
||||
<img src="${data.map}" alt="Dungeon Map" />
|
||||
</div>
|
||||
</div>
|
||||
<footer>Scrollsmith • © ${new Date().getFullYear()}</footer>
|
||||
</div>
|
||||
` : ''}
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -1,21 +1,34 @@
|
||||
import puppeteer from "puppeteer";
|
||||
import { dungeonTemplate } from "./dungeonTemplate.js";
|
||||
|
||||
import fs from 'fs/promises';
|
||||
import fs from "fs/promises";
|
||||
|
||||
export async function generatePDF(data, outputPath = "dungeon.pdf") {
|
||||
const browser = await puppeteer.launch({
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox']
|
||||
args: ["--no-sandbox", "--disable-setuid-sandbox"],
|
||||
});
|
||||
|
||||
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 toBase64DataUrl = (buffer) =>
|
||||
`data:image/png;base64,${buffer.toString("base64")}`;
|
||||
|
||||
const html = dungeonTemplate(data);
|
||||
const readImageData = async (path) =>
|
||||
fs
|
||||
.readFile(path)
|
||||
.then(toBase64DataUrl)
|
||||
.catch(() => {
|
||||
console.warn(
|
||||
"Warning: Could not read image file, proceeding without map in PDF",
|
||||
);
|
||||
return null;
|
||||
});
|
||||
|
||||
const imageData = data.map ? await readImageData(data.map) : null;
|
||||
const dataWithImage = imageData
|
||||
? { ...data, map: imageData }
|
||||
: (({ map, ...rest }) => rest)(data);
|
||||
|
||||
const html = dungeonTemplate(dataWithImage);
|
||||
await page.setContent(html, { waitUntil: "networkidle0" });
|
||||
|
||||
await page.pdf({
|
||||
@@ -23,7 +36,7 @@ export async function generatePDF(data, outputPath = "dungeon.pdf") {
|
||||
format: "A4",
|
||||
landscape: true,
|
||||
printBackground: true,
|
||||
preferCSSPageSize: true
|
||||
preferCSSPageSize: true,
|
||||
});
|
||||
|
||||
await browser.close();
|
||||
|
||||
@@ -2,8 +2,9 @@ import sharp from 'sharp';
|
||||
import path from "path";
|
||||
import { mkdir, writeFile } from "fs/promises";
|
||||
import { fileURLToPath } from "url";
|
||||
import { callOllama } from "./ollamaClient.js";
|
||||
import { callOllama, OLLAMA_MODEL } from "./ollamaClient.js";
|
||||
|
||||
const COMFYUI_ENABLED = process.env.COMFYUI_ENABLED !== 'false';
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const COMFYUI_URL = process.env.COMFYUI_URL || "http://localhost:8188";
|
||||
|
||||
@@ -62,7 +63,9 @@ Input:
|
||||
${flavor}
|
||||
|
||||
Output:`,
|
||||
"gemma3n:e4b", 3, "Generate Visual Prompt"
|
||||
OLLAMA_MODEL,
|
||||
3,
|
||||
"Generate Visual Prompt"
|
||||
);
|
||||
|
||||
const accentColor = selectRandomAccentColor();
|
||||
@@ -228,6 +231,11 @@ async function generateImageViaComfyUI(prompt, filename) {
|
||||
export async function generateDungeonImages({ flavor }) {
|
||||
console.log("Generating dungeon image...");
|
||||
|
||||
if (!COMFYUI_ENABLED) {
|
||||
console.log("ComfyUI image generation disabled via .env; using existing upscaled image.");
|
||||
return path.join(__dirname, "dungeon_upscaled.png");
|
||||
}
|
||||
|
||||
const finalPrompt = await generateVisualPrompt(flavor);
|
||||
console.log("Engineered visual prompt:\n", finalPrompt);
|
||||
|
||||
|
||||
14
index.js
14
index.js
@@ -1,18 +1,25 @@
|
||||
import 'dotenv/config';
|
||||
import "dotenv/config";
|
||||
import { generateDungeon } from "./dungeonGenerator.js";
|
||||
import { generateDungeonImages } from "./imageGenerator.js";
|
||||
import { generatePDF } from "./generatePDF.js";
|
||||
import { OLLAMA_MODEL } from "./ollamaClient.js";
|
||||
|
||||
// Utility to create a filesystem-safe filename from the dungeon title
|
||||
function slugify(text) {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-') // replace non-alphanumeric with hyphens
|
||||
.replace(/^-+|-+$/g, ''); // trim leading/trailing hyphens
|
||||
.replace(/[^a-z0-9]+/g, "-") // replace non-alphanumeric with hyphens
|
||||
.replace(/^-+|-+$/g, ""); // trim leading/trailing hyphens
|
||||
}
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
if (!process.env.OLLAMA_API_URL) {
|
||||
throw new Error("OLLAMA_API_URL environment variable is required");
|
||||
}
|
||||
console.log("Using Ollama API URL:", process.env.OLLAMA_API_URL);
|
||||
console.log("Using Ollama model:", OLLAMA_MODEL);
|
||||
|
||||
// Generate the dungeon data
|
||||
const dungeonData = await generateDungeon();
|
||||
|
||||
@@ -30,5 +37,6 @@ function slugify(text) {
|
||||
console.log(`Dungeon PDF successfully generated: ${filename}`);
|
||||
} catch (err) {
|
||||
console.error("Error generating dungeon:", err);
|
||||
process.exit(1);
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -1,47 +1,47 @@
|
||||
const OLLAMA_API_URL = process.env.OLLAMA_API_URL;
|
||||
const OLLAMA_API_KEY = process.env.OLLAMA_API_KEY;
|
||||
export const OLLAMA_MODEL = process.env.OLLAMA_MODEL || "gemma3:4b";
|
||||
|
||||
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
|
||||
.replace(/^#+\s*/gm, "")
|
||||
.replace(/\*\*(.*?)\*\*/g, "$1")
|
||||
.replace(/[*_`]/g, "")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export async function callOllama(prompt, model = "gemma3n:e4b", retries = 5, stepName = "unknown") {
|
||||
const isUsingOpenWebUI = !!OLLAMA_API_KEY;
|
||||
function inferApiType(url) {
|
||||
return url?.includes("/api/chat/completions") ? "open-webui" : "direct";
|
||||
}
|
||||
|
||||
async function sleep(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function callOllamaBase(prompt, model, retries, stepName, apiType) {
|
||||
const isUsingOpenWebUI = apiType === "open-webui";
|
||||
|
||||
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`);
|
||||
console.log(
|
||||
`\n[${stepName}] Sending prompt (attempt ${attempt}/${retries})`,
|
||||
);
|
||||
console.log(
|
||||
`Prompt: ${promptCharCount} chars, ~${promptWordCount} words`,
|
||||
);
|
||||
|
||||
const headers = { "Content-Type": "application/json" };
|
||||
|
||||
if (isUsingOpenWebUI) {
|
||||
if (isUsingOpenWebUI && OLLAMA_API_KEY) {
|
||||
headers["Authorization"] = `Bearer ${OLLAMA_API_KEY}`;
|
||||
}
|
||||
|
||||
const body = isUsingOpenWebUI
|
||||
? {
|
||||
model,
|
||||
messages: [{ role: "user", content: prompt }],
|
||||
}
|
||||
: {
|
||||
model,
|
||||
messages: [{ role: "user", content: prompt }],
|
||||
stream: false,
|
||||
};
|
||||
? { model, messages: [{ role: "user", content: prompt }] }
|
||||
: { model, prompt, stream: false };
|
||||
|
||||
const response = await fetch(OLLAMA_API_URL, {
|
||||
method: "POST",
|
||||
@@ -49,24 +49,24 @@ export async function callOllama(prompt, model = "gemma3n:e4b", retries = 5, ste
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error(`Ollama request failed: ${response.status} ${response.statusText}`);
|
||||
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;
|
||||
: data.response;
|
||||
|
||||
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`);
|
||||
console.log(
|
||||
`[${stepName}] Received: ${rawText.length} chars, ~${rawText.split(/\s+/).length} words`,
|
||||
);
|
||||
|
||||
return cleaned;
|
||||
|
||||
} catch (err) {
|
||||
console.warn(`[${stepName}] Attempt ${attempt} failed: ${err.message}`);
|
||||
if (attempt === retries) throw err;
|
||||
@@ -76,3 +76,23 @@ export async function callOllama(prompt, model = "gemma3n:e4b", retries = 5, ste
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function callOllama(
|
||||
prompt,
|
||||
model = OLLAMA_MODEL,
|
||||
retries = 5,
|
||||
stepName = "unknown",
|
||||
) {
|
||||
const apiType = inferApiType(OLLAMA_API_URL);
|
||||
return callOllamaBase(prompt, model, retries, stepName, apiType);
|
||||
}
|
||||
|
||||
export async function callOllamaExplicit(
|
||||
prompt,
|
||||
model = OLLAMA_MODEL,
|
||||
retries = 5,
|
||||
stepName = "unknown",
|
||||
apiType = "direct",
|
||||
) {
|
||||
return callOllamaBase(prompt, model, retries, stepName, apiType);
|
||||
}
|
||||
|
||||
586
package-lock.json
generated
586
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user