ai vs human try 0001

This commit is contained in:
2026-07-28 17:54:22 +02:00
parent 54f115204f
commit efed783e25
+148 -93
View File
@@ -4,7 +4,6 @@ import (
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
"html/template"
"io" "io"
"net/http" "net/http"
"os" "os"
@@ -22,7 +21,7 @@ type Choice struct {
type StoryNode struct { type StoryNode struct {
ID string `json:"id"` ID string `json:"id"`
Title string `json:"title"` Title string `json:"title"`
Content template.HTML `json:"content"` Content string `json:"content"` // Reiner String, JSON kümmert sich um das Escaping des HTMLs
Choices []Choice `json:"choices"` Choices []Choice `json:"choices"`
IsReboot bool `json:"isReboot"` IsReboot bool `json:"isReboot"`
IsEnd bool `json:"isEnd"` IsEnd bool `json:"isEnd"`
@@ -38,14 +37,6 @@ type StoryGraph struct {
DeadEndNodes []string `json:"deadEndNodes"` DeadEndNodes []string `json:"deadEndNodes"`
} }
// Struct für das saubere Injezieren der Frontend-Komponenten
type TemplateContext struct {
Graph template.JS
CSS template.CSS
Logic template.JS
UI template.JS
}
var ( var (
adocNodeRegex = regexp.MustCompile(`\[\[([a-zA-Z0-9_\-]+)\]\]`) adocNodeRegex = regexp.MustCompile(`\[\[([a-zA-Z0-9_\-]+)\]\]`)
adocChoiceRegex = regexp.MustCompile(`<<([a-zA-Z0-9_\-]+)\s*,\s*([^>]+)>>`) adocChoiceRegex = regexp.MustCompile(`<<([a-zA-Z0-9_\-]+)\s*,\s*([^>]+)>>`)
@@ -55,51 +46,123 @@ var (
) )
func main() { func main() {
dirPtr := flag.String("dir", ".", "Verzeichnis mit AsciiDoc/Markdown Dateien") dirPtr := flag.String("dir", "./stories", "Verzeichnis mit AsciiDoc/Markdown Dateien")
outPtr := flag.String("out", "export/story.html", "Zielpfad für den Dateiexport") frontendPtr := flag.String("frontend", "./frontend", "Pfad zum Verzeichnis der statischen Frontend-Dateien")
tmplPtr := flag.String("tmpl", "template.html", "Pfad zur HTML Template-Datei") outPtr := flag.String("out", "export/story.html", "Zielpfad für den Dateiexport (Single-File HTML)")
servePtr := flag.Bool("serve", false, "Startet den API- & Preview-Server") servePtr := flag.Bool("serve", false, "Startet den API- & Preview-Server, statt zu exportieren")
portPtr := flag.Int("port", 8080, "Port für den Server") portPtr := flag.Int("port", 3344, "Port für den Server")
flag.Parse() flag.Parse()
fmt.Println("\033[1;36m=== Computer Historyz :: CYOA Engine (Modular) ===\033[0m") fmt.Println("\033[1;36m=== Computer Historyz :: CYOA Engine ===\033[0m")
if info, err := os.Stat(*frontendPtr); os.IsNotExist(err) || !info.IsDir() {
fmt.Printf("\033[1;33m[WARNUNG]\033[0m Frontend-Verzeichnis '%s' nicht gefunden!\n", *frontendPtr)
}
if *servePtr { if *servePtr {
startServer(*portPtr, *dirPtr, *outPtr, *tmplPtr) startServer(*portPtr, *dirPtr, *frontendPtr)
return return
} }
// --- EXPORT MODUS ---
fmt.Printf("\033[1;34m[EXPORT]\033[0m Kompiliere Story-Graph via Asciidoctor aus '%s'...\n", *dirPtr)
graph := loadStoryGraphFromDir(*dirPtr) graph := loadStoryGraphFromDir(*dirPtr)
validateGraph(graph) validateGraph(graph)
outDir := filepath.Dir(*outPtr) outDir := filepath.Dir(*outPtr)
os.MkdirAll(outDir, 0755) os.MkdirAll(outDir, 0755)
if err := generateHTMLFile(graph, *outPtr, *tmplPtr); err != nil { err := buildSingleFileExport(graph, *frontendPtr, *outPtr)
fmt.Printf("\033[1;31m[FEHLER]\033[0m %v\n", err) if err != nil {
fmt.Printf("\033[1;31m[FEHLER]\033[0m Build fehlgeschlagen: %v\n", err)
os.Exit(1) os.Exit(1)
} }
fmt.Printf("\033[1;32m[ERFOLG]\033[0m Story modular generiert -> \033[1;33m%s\033[0m\n", *outPtr) fmt.Printf("\033[1;32m[ERFOLG]\033[0m Single-File Story exportiert -> \033[1;33m%s\033[0m\n", *outPtr)
} }
func readAsset(basePath, filename string) string { func startServer(port int, watchDir string, frontendDir string) {
b, err := os.ReadFile(filepath.Join(filepath.Dir(basePath), filename)) addr := fmt.Sprintf(":%d", port)
http.HandleFunc("/api/graph", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodPost {
bodyBytes, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return fmt.Sprintf("/* %s nicht gefunden */", filename) http.Error(w, `{"error": "Daten defekt"}`, http.StatusBadRequest)
} return
return string(b) }
graph := &StoryGraph{Nodes: make(map[string]*StoryNode)}
parseContent(string(bodyBytes), "API_POST_Stream", graph)
validateGraph(graph)
json.NewEncoder(w).Encode(graph)
fmt.Println("\033[1;34m[POST-API]\033[0m Story-Graph verarbeitet.")
return
}
if r.Method == http.MethodGet {
graph := loadStoryGraphFromDir(watchDir)
validateGraph(graph)
json.NewEncoder(w).Encode(graph)
}
})
fs := http.FileServer(http.Dir(frontendDir))
http.Handle("/", fs)
fmt.Printf("\n\033[1;32m[SERVER LÄUFT]\033[0m http://localhost:%d\n", port)
if err := http.ListenAndServe(addr, nil); err != nil {
fmt.Printf("\033[1;31m[FEHLER]\033[0m %v\n", err)
}
}
func buildSingleFileExport(graph *StoryGraph, frontendDir string, outPath string) error {
indexPath := filepath.Join(frontendDir, "index.html")
htmlBytes, err := os.ReadFile(indexPath)
if err != nil {
return fmt.Errorf("konnte %s nicht lesen: %v", indexPath, err)
}
htmlStr := string(htmlBytes)
cssBytes, _ := os.ReadFile(filepath.Join(frontendDir, "style.css"))
logicBytes, _ := os.ReadFile(filepath.Join(frontendDir, "engine_logic.js"))
uiBytes, _ := os.ReadFile(filepath.Join(frontendDir, "engine_ui.js"))
graphJson, _ := json.Marshal(graph)
// CSS ersetzen
htmlStr = strings.Replace(htmlStr, `<link rel="stylesheet" href="style.css">`, fmt.Sprintf("<style>\n%s\n</style>", string(cssBytes)), 1)
// JS ersetzen
htmlStr = strings.Replace(htmlStr, `<script src="engine_logic.js"></script>`, fmt.Sprintf("<script>\n%s\n</script>", string(logicBytes)), 1)
htmlStr = strings.Replace(htmlStr, `<script src="engine_ui.js"></script>`, fmt.Sprintf("<script>\n%s\n</script>", string(uiBytes)), 1)
// JSON State in den Data-Block pressen
re := regexp.MustCompile(`(?s)<script id="story-data" type="application/json">.*?</script>`)
htmlStr = re.ReplaceAllString(htmlStr, fmt.Sprintf("<script id=\"story-data\" type=\"application/json\">\n%s\n</script>", string(graphJson)))
return os.WriteFile(outPath, []byte(htmlStr), 0644)
}
// renderAsciidoctor piped rohen AsciiDoc Text in den lokalen Container-Prozess
func renderAsciidoctor(text string) string {
if strings.TrimSpace(text) == "" {
return ""
} }
func renderAsciidoctor(text string) template.HTML {
if strings.TrimSpace(text) == "" { return "" }
cmd := exec.Command("asciidoctor", "--embedded", "-") cmd := exec.Command("asciidoctor", "--embedded", "-")
cmd.Stdin = strings.NewReader(text) cmd.Stdin = strings.NewReader(text)
out, err := cmd.Output() out, err := cmd.Output()
if err != nil { if err != nil {
fallback := strings.ReplaceAll(text, "\n", "<br>") fmt.Printf("\033[1;33m[WARNUNG]\033[0m Asciidoctor Rendering fehlgeschlagen: %v\n", err)
return template.HTML(fallback) return strings.ReplaceAll(text, "\n", "<br>")
} }
return template.HTML(string(out))
return string(out)
} }
func cleanBodyText(raw string) string { func cleanBodyText(raw string) string {
@@ -121,38 +184,72 @@ func parseContent(rawContent string, sourceName string, graph *StoryGraph) {
currentBody.Reset() currentBody.Reset()
} }
nodeID := matches[1] nodeID := matches[1]
currentNode = &StoryNode{ ID: nodeID, Title: nodeID, Choices: make([]Choice, 0), FileSource: sourceName, Metadata: make(map[string]string) } currentNode = &StoryNode{
if graph.StartNodeID == "" || nodeID == "start" || nodeID == "node_start" { graph.StartNodeID = nodeID } ID: nodeID,
Title: nodeID,
Choices: make([]Choice, 0),
FileSource: sourceName,
Metadata: make(map[string]string),
}
if graph.StartNodeID == "" || nodeID == "start" || nodeID == "node_start" {
graph.StartNodeID = nodeID
}
continue continue
} }
if currentNode == nil { if currentNode == nil {
if strings.TrimSpace(line) != "" { if strings.TrimSpace(line) != "" {
baseID := "start" baseID := "start"
if sourceName != "API_POST_Stream" { baseID = strings.TrimSuffix(filepath.Base(sourceName), filepath.Ext(sourceName)) } if sourceName != "API_POST_Stream" {
currentNode = &StoryNode{ ID: baseID, Title: baseID, Choices: make([]Choice, 0), FileSource: sourceName, Metadata: make(map[string]string) } baseID = strings.TrimSuffix(filepath.Base(sourceName), filepath.Ext(sourceName))
if graph.StartNodeID == "" { graph.StartNodeID = baseID } }
} else { continue } currentNode = &StoryNode{
ID: baseID,
Title: baseID,
Choices: make([]Choice, 0),
FileSource: sourceName,
Metadata: make(map[string]string),
}
if graph.StartNodeID == "" {
graph.StartNodeID = baseID
}
} else {
continue
}
} }
if mMatches := metaRegex.FindStringSubmatch(line); len(mMatches) > 2 { if mMatches := metaRegex.FindStringSubmatch(line); len(mMatches) > 2 {
currentNode.Metadata[strings.ToLower(mMatches[1])] = strings.TrimSpace(mMatches[2]); continue currentNode.Metadata[strings.ToLower(mMatches[1])] = strings.TrimSpace(mMatches[2])
continue
} }
if hMatches := headingRegex.FindStringSubmatch(line); len(hMatches) > 1 && currentNode.Title == currentNode.ID { if hMatches := headingRegex.FindStringSubmatch(line); len(hMatches) > 1 && currentNode.Title == currentNode.ID {
currentNode.Title = strings.TrimSpace(hMatches[1]) currentNode.Title = strings.TrimSpace(hMatches[1])
} }
if cMatches := adocChoiceRegex.FindAllStringSubmatch(line, -1); len(cMatches) > 0 { if cMatches := adocChoiceRegex.FindAllStringSubmatch(line, -1); len(cMatches) > 0 {
for _, match := range cMatches { currentNode.Choices = append(currentNode.Choices, Choice{TargetID: match[1], Text: strings.TrimSpace(match[2])}) } for _, match := range cMatches {
currentNode.Choices = append(currentNode.Choices, Choice{TargetID: match[1], Text: strings.TrimSpace(match[2])})
} }
}
if mMatches := mdChoiceRegex.FindAllStringSubmatch(line, -1); len(mMatches) > 0 { if mMatches := mdChoiceRegex.FindAllStringSubmatch(line, -1); len(mMatches) > 0 {
for _, match := range mMatches { currentNode.Choices = append(currentNode.Choices, Choice{TargetID: match[2], Text: strings.TrimSpace(match[1])}) } for _, match := range mMatches {
currentNode.Choices = append(currentNode.Choices, Choice{TargetID: match[2], Text: strings.TrimSpace(match[1])})
}
} }
lowerLine := strings.ToLower(line) lowerLine := strings.ToLower(line)
if strings.Contains(lowerLine, "[reboot]") || strings.Contains(lowerLine, "speicherabbild") { currentNode.IsReboot = true } if strings.Contains(lowerLine, "[reboot]") || strings.Contains(lowerLine, "speicherabbild") {
if strings.Contains(lowerLine, "[ende]") || strings.Contains(lowerLine, "[end]") { currentNode.IsEnd = true } currentNode.IsReboot = true
}
if strings.Contains(lowerLine, "[ende]") || strings.Contains(lowerLine, "[end]") {
currentNode.IsEnd = true
}
currentBody.WriteString(line + "\n") currentBody.WriteString(line + "\n")
} }
if currentNode != nil { if currentNode != nil {
currentNode.Content = renderAsciidoctor(cleanBodyText(currentBody.String())) currentNode.Content = renderAsciidoctor(cleanBodyText(currentBody.String()))
graph.Nodes[currentNode.ID] = currentNode graph.Nodes[currentNode.ID] = currentNode
@@ -166,7 +263,10 @@ func loadStoryGraphFromDir(rootDir string) *StoryGraph {
ext := strings.ToLower(filepath.Ext(path)) ext := strings.ToLower(filepath.Ext(path))
if ext != ".adoc" && ext != ".md" { return nil } if ext != ".adoc" && ext != ".md" { return nil }
contentBytes, err := os.ReadFile(path) contentBytes, err := os.ReadFile(path)
if err == nil { parseContent(string(contentBytes), filepath.Base(path), graph) } if err == nil {
relPath, _ := filepath.Rel(rootDir, path)
parseContent(string(contentBytes), relPath, graph)
}
return nil return nil
}) })
return graph return graph
@@ -178,60 +278,15 @@ func validateGraph(g *StoryGraph) {
for id, node := range g.Nodes { for id, node := range g.Nodes {
for _, choice := range node.Choices { for _, choice := range node.Choices {
referenced[choice.TargetID] = true referenced[choice.TargetID] = true
if _, exists := g.Nodes[choice.TargetID]; !exists { g.BrokenLinks = append(g.BrokenLinks, fmt.Sprintf("%s -> %s (in %s)", id, choice.TargetID, node.FileSource)) } if _, exists := g.Nodes[choice.TargetID]; !exists {
} g.BrokenLinks = append(g.BrokenLinks, fmt.Sprintf("%s -> %s (in %s)", id, choice.TargetID, node.FileSource))
if len(node.Choices) == 0 && !node.IsReboot && !node.IsEnd { g.DeadEndNodes = append(g.DeadEndNodes, id) }
}
for id := range g.Nodes { if !referenced[id] { g.OrphanNodes = append(g.OrphanNodes, id) } }
}
func getContext(graph *StoryGraph, tmplPath string) TemplateContext {
graphJson, _ := json.Marshal(graph)
return TemplateContext{
Graph: template.JS(graphJson),
CSS: template.CSS(readAsset(tmplPath, "style.css")),
Logic: template.JS(readAsset(tmplPath, "engine_logic.js")),
UI: template.JS(readAsset(tmplPath, "engine_ui.js")),
} }
} }
if len(node.Choices) == 0 && !node.IsReboot && !node.IsEnd {
func generateHTMLFile(g *StoryGraph, outPath string, tmplPath string) error { g.DeadEndNodes = append(g.DeadEndNodes, id)
tmpl, err := template.ParseFiles(tmplPath)
if err != nil { return fmt.Errorf("Template-Fehler: %v", err) }
f, err := os.Create(outPath)
if err != nil { return err }
defer f.Close()
return tmpl.Execute(f, getContext(g, tmplPath))
} }
func startServer(port int, watchDir string, htmlPath string, tmplPath string) {
addr := fmt.Sprintf(":%d", port)
fmt.Printf("\n\033[1;32m[CONTAINER-API LÄUFT]\033[0m Port: %d | Nutzt Template: %s\n", port, tmplPath)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method == http.MethodPost {
bodyBytes, err := io.ReadAll(r.Body)
if err != nil { http.Error(w, "Daten defekt", http.StatusBadRequest); return }
graph := &StoryGraph{Nodes: make(map[string]*StoryNode)}
parseContent(string(bodyBytes), "API_POST_Stream", graph)
validateGraph(graph)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl, err := template.ParseFiles(tmplPath)
if err != nil { http.Error(w, "Template-Fehler: "+err.Error(), http.StatusInternalServerError); return }
tmpl.Execute(w, getContext(graph, tmplPath))
fmt.Println("\033[1;34m[POST-API]\033[0m Modularer Stack gerendert.")
return
} }
if r.Method == http.MethodGet { for id := range g.Nodes {
freshGraph := loadStoryGraphFromDir(watchDir) if !referenced[id] { g.OrphanNodes = append(g.OrphanNodes, id) }
_ = generateHTMLFile(freshGraph, htmlPath, tmplPath)
http.ServeFile(w, r, htmlPath)
} }
})
http.ListenAndServe(addr, nil)
} }