File size: 1,787 Bytes
deb83c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import json
import os
from typing import List
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from model import generate_structure

app = FastAPI()
STRUCTURE_FILE = "structures.json"
structure_store = []

class Prompt(BaseModel):
    text: str

class Structure(BaseModel):
    name: str
    description: str
    required_blocks: List[str]
    tags: List[str]

@app.post("/generate")
def generate(prompt: Prompt):
    result = generate_structure(prompt.text)
    return {"response": result}

@app.post("/register_structure")
def register_structure(structure: Structure):
    # Load existing structures
    structures = []
    if os.path.exists(STRUCTURE_FILE):
        with open(STRUCTURE_FILE, "r") as f:
            try:
                structures = json.load(f)
            except json.JSONDecodeError:
                pass  # File was empty or invalid

    # Check for duplicates
    for s in structures:
        if s["name"] == structure.name:
            raise HTTPException(status_code=400, detail="Structure with this name already exists")

    # Append and save
    structures.append(structure.dict())
    with open(STRUCTURE_FILE, "w") as f:
        json.dump(structures, f, indent=2)

    return {"message": "Structure registered successfully"}

@app.get("/structures", response_class=HTMLResponse)
def list_structures():
    html = "<h2>Registered Structures</h2><table border='1'><tr><th>Name</th><th>Description</th><th>Required Blocks</th><th>Tags</th></tr>"
    for structure in structure_store:
        html += f"<tr><td>{structure.name}</td><td>{structure.description}</td><td>{', '.join(structure.required_blocks)}</td><td>{', '.join(structure.tags)}</td></tr>"
    html += "</table>"
    return html