summaryrefslogtreecommitdiff
path: root/Biz/Storybook.py
blob: 3659c371db362c36bd5fdd81e0d028d810bc0e93 (plain)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
"""Storybook Generator Application.

This application generates a children's storybook using the OpenAI API.

The user can select a theme, specify the main character's name, and choose a
setting. The app generates a 10-page storybook with images.

The tech stack is: Python, Ludic, and HTMX. All of the code is in
this single file.

"""

# : out storybook
# : dep ludic
# : dep openai
# : dep uvicorn
# : dep starlette
# : dep sqids
# : dep requests
# : dep types-requests
import json
import logging
import ludic
import ludic.catalog.buttons as buttons
import ludic.catalog.forms as forms
import ludic.catalog.headers as headers
import ludic.catalog.layouts as layouts
import ludic.catalog.pages as pages
import ludic.catalog.typography as typography
import ludic.web
import Omni.Log as Log
import openai
import pathlib
import requests
import sqids
import starlette.testclient
import sys
import time
import typing
import unittest
import uvicorn

MOCK = True
DEBUG = False
DATA_DIR = pathlib.Path("_/var/storybook/")

app = ludic.web.LudicApp(debug=DEBUG)
Sqids = sqids.Sqids()


def main() -> None:
    """Run the Ludic application."""
    if sys.argv[1] == "test":
        test()
    else:
        move()


def move() -> None:
    """Run the application."""
    Log.setup(logging.DEBUG if DEBUG else logging.ERROR)
    local = "127.0.0.1"
    uvicorn.run(app, host=local)


def test() -> None:
    """Run the unittest suite manually."""
    Log.setup(logging.DEBUG if DEBUG else logging.ERROR)
    suite = unittest.TestSuite()
    tests = [StorybookTest, IndexTest, StoryTest, ImagesTest]
    suite.addTests([
        unittest.defaultTestLoader.loadTestsFromTestCase(tc) for tc in tests
    ])
    unittest.TextTestRunner(verbosity=2).run(suite)


def const(s: str) -> str:
    """Just returns the input."""
    return s


class PageContent(ludic.attrs.Attrs):
    """Represents the content of a single page in the storybook."""

    image_prompt: str
    text: str


class Page(ludic.attrs.Attrs):
    """Represents a single page in the storybook."""

    story_id: str
    page_number: int
    content: PageContent


class Image(ludic.attrs.Attrs):
    """Represents an image associated with a story page."""

    story_id: str
    page: int
    prompt: typing.Annotated[str, const]
    original_url: typing.Annotated[str, const]
    path: pathlib.Path


class Prompt(ludic.attrs.Attrs):
    """Represents a prompt for generating an image."""

    text: typing.Annotated[str, const]


class StoryInputs(ludic.attrs.Attrs):
    """Represents story inputs from the user."""

    theme: typing.Annotated[str, const]
    character: typing.Annotated[str, const]
    setting: typing.Annotated[str, const]
    moral: typing.Annotated[str, const]


example_story: dict[str, str] = {
    "theme": "Christian",
    "character": "Lia and her pet bunny",
    "setting": "A suburban park",
    "moral": "Honor thy mother and father",
}


class Story(ludic.attrs.Attrs):
    """Represents a full generated story."""

    id: typing.Annotated[str, const]
    pages: typing.Annotated[list[Page], const]


system_prompt: str = (
    "You are an author and illustrator of childrens books. "
    "Each book is 10 pages long. "
    "All output must be in valid JSON. "
    "Don't add explanation or markdown formatting beyond the JSON. "
    "In your output, include the text on the page and a description of the "
    "image to be generated with an AI image generator."
)


def user_prompt(story: StoryInputs) -> str:
    """Generate the user prompt based on the story details."""
    return " ".join([
        "Write a story with the following details.",
        "Output must be in valid JSON where each page is an array of text and"
        "image like the following example:",
        """[{"text": "<text of the story>",""",
        """"image": "<description of illustration>"}...],""",
        f"Character: {story['character']}\n",
        f"Setting: {story['setting']}\n",
        f"Theme: {story['theme']}\n",
        f"Moral: {story['moral']}\n",
    ])


def _openai_generate_text(
    story: StoryInputs,
) -> openai.types.chat.ChatCompletion:
    """Generate story text using the OpenAI API."""
    messages: list[
        openai.types.chat.ChatCompletionUserMessageParam
        | openai.types.chat.ChatCompletionSystemMessageParam
    ] = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt(story)},
    ]
    client = openai.OpenAI()
    return client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages,
        max_tokens=1500,
    )


def generate_pages(inputs: StoryInputs) -> list[PageContent]:
    """Generate the text for a story and update its pages.

    Raises:
        ValueError: when openAI response is bad
    """
    # when developing, don't run up the OpenAI tab
    if MOCK:
        name = inputs["character"]
        return [
            PageContent(
                text=f"A story about {name}...",
                image_prompt="Lorem ipsum..",
            )
            for n in range(10)
        ]
    response = _openai_generate_text(inputs)
    content = response.choices[0].message.content
    if content is None:
        msg = "content is none"
        raise ValueError(msg)
    response_messages = json.loads(content)
    return [
        PageContent(
            text=msg["text"],
            image_prompt=msg["image"],
        )
        for msg in response_messages
    ]


class StoryTest(unittest.TestCase):
    """Unit test case for the Story class and related functions."""

    def test_story_creation(self) -> None:
        """Creates a story with 10 pages."""
        s = StoryInputs(example_story)  # type: ignore[misc]
        pages = generate_pages(s)
        self.assertIsNotNone(pages)
        self.assertEqual(len(pages), 10)


class AppPage(
    ludic.components.Component[ludic.types.AnyChildren, ludic.attrs.NoAttrs],
):
    """HTML wrapper for the app."""

    @typing.override
    def render(self) -> pages.HtmlPage:
        return pages.HtmlPage(
            pages.Head(
                ludic.html.meta(charset="utf-8"),
                ludic.html.meta(
                    name="viewport",
                    content="width=device-width, initial-scale=1",
                ),
                ludic.html.style.load(),
                title="Storybook",
                favicon="favicon.ico",
                load_styles=True,
            ),
            pages.Body(
                layouts.Center(layouts.Stack(*self.children)),
                htmx_version="latest",
            ),
        )


@app.get("/")
def index(_: ludic.web.Request) -> AppPage:
    """Render the main page."""
    return AppPage(
        headers.H1("Storybook Generator"),
        StoriesForm(),
        ludic.html.div(id="story"),
    )


class IndexTest(unittest.TestCase):
    """Test the home page."""

    def setUp(self) -> None:
        """Create test client."""
        self.client = starlette.testclient.TestClient(app)

    def test_index(self) -> None:
        """The index page loads successfully."""
        response = self.client.get("/")
        self.assertEqual(response.status_code, 200)
        self.assertIn("Storybook Generator", response.text)


db_last_story_id: str = "bM"  # sqid.encode([0])


class Database(ludic.attrs.Attrs):
    """Represents a simple in-memory database for storing stories and images."""

    stories: dict[str, Story]
    images: dict[str, Image]


db: Database = Database(stories={}, images={})


@app.endpoint("/pages/{story_id:str}/{page:int}")
class Pages(ludic.web.Endpoint[Page]):
    """Resource for retrieving individual pages in a story."""

    @classmethod
    def get(cls, story_id: str, page: int) -> typing.Self:
        """Get a single page."""
        story = Stories.get(story_id)
        story_page = Page(**story.attrs["pages"][page])
        return cls(**story_page)

    @typing.override
    def render(self) -> ludic.base.BaseElement:
        """Render a single page as HTML."""
        return layouts.Box(
            layouts.Stack(
                ludic.html.img(
                    src="//placehold.co/256/000000/FFFFFF",
                    hx_post=app.url_path_for(
                        "Images",
                        story_id=self.attrs["story_id"],
                        page=self.attrs["page_number"],
                    ),
                    hx_trigger="load",
                    hx_swap="outerHTML:beforeend",
                    hx_vals=json.dumps(
                        Prompt(text=self.attrs["content"]["image_prompt"]),
                    ),
                    width=256,
                    height=256,
                ),
                typography.Paragraph(self.attrs["content"]["text"]),
            ),
        )


@app.endpoint("/images/{story_id:str}/{page:int}")
class Images(ludic.web.Endpoint[Image]):
    """Endpoint for handling image-related operations."""

    @classmethod
    def get(cls, story_id: str, page: int) -> ludic.web.responses.Response:
        """Load the image from the database, if not found return 404.

        Raises:
            NotFoundError: If the image is not found.
        """
        if image := Images.load_by_id(story_id, page):
            return ludic.web.responses.FileResponse(image["path"])
        msg = "no image found"
        logging.error(msg)
        raise ludic.web.exceptions.NotFoundError(msg)

    @classmethod
    def post(
        cls,
        story_id: str,
        page: int,
        data: ludic.web.parsers.Parser[Prompt],
    ) -> ludic.web.responses.Response:
        """Create a new image, or retrieve an existing one."""
        Prompt(**data.validate())
        path = cls.gen_path(story_id, page)
        if path.exists():
            return cls.get(story_id, page)
        return cls.put(story_id, page, data)

    @classmethod
    def put(
        cls,
        story_id: str,
        page: int,
        data: ludic.web.parsers.Parser[Prompt],
    ) -> ludic.web.responses.Response:
        """Create a new image, overwriting if one exists.

        Raises:
            InternalServerError: If there is an error getting the image from the
                OpenAI API.
        """
        if MOCK:
            # Simulate slow image generation
            time.sleep(3)
            return ludic.web.responses.FileResponse(
                DATA_DIR / "images" / "placeholder.jpg",
            )
        client = openai.OpenAI()
        prompt = Prompt(**data.validate())
        image_response = client.images.generate(
            prompt=prompt["text"],
            n=1,
            size="256x256",
        )
        url = image_response.data[0].url
        if url is None:
            msg = "error getting image from OpenAI"
            logging.error(msg)
            raise ludic.web.exceptions.InternalServerError(msg)
        image = Image(
            story_id=story_id,
            page=page,
            prompt=prompt["text"],
            original_url=url,
            path=cls.gen_path(story_id, page),
        )
        cls.save(image)
        return ludic.web.responses.FileResponse(image["path"])

    @classmethod
    def gen_image_id(cls, story_id: str, page: int) -> str:
        """Generate a unique image ID based on the story ID and page number."""
        story_id_num = Sqids.decode(story_id)[0]
        return Sqids.encode([story_id_num, page])

    @classmethod
    def load_by_id(cls, story_id: str, page: int) -> Image | None:
        """Load an image by its story ID and page number."""
        cls.gen_image_id(story_id, page)
        path = cls.gen_path(story_id, page)
        if path.exists():
            return Image(
                story_id=story_id,
                page=page,
                path=path,
                # Consider storing prompt and original_url in sqlite
                prompt="",
                original_url="",
            )
        return None

    @classmethod
    def gen_path(cls, story_id: str, page: int) -> pathlib.Path:
        """Generate the file path for an image."""
        image_id = cls.gen_image_id(story_id, page)
        return pathlib.Path(
            DATA_DIR / "images" / story_id / image_id,
        ).with_suffix(".jpg")

    @classmethod
    def save(cls, image: Image) -> None:
        """Save an image to the file system."""
        response = requests.get(image["original_url"], timeout=10)
        pathlib.Path(image["path"]).write_bytes(response.content)

    @classmethod
    def read(cls, image: Image) -> bytes:
        """Read an image from the file system."""
        return pathlib.Path(image["path"]).read_bytes()

    @typing.override
    def render(self) -> ludic.base.BaseElement:
        return ludic.html.img(
            src=app.url_path_for(
                "Images",
                story_id=self.attrs["story_id"],
                page=self.attrs["page"],
            ),
        )


class ImagesTest(unittest.TestCase):
    """Test the Images endpoint."""

    def setUp(self) -> None:
        """Create test client."""
        self.client = starlette.testclient.TestClient(app)

    def test_image_post(self) -> None:
        """Can POST an Image successfully."""
        response = self.client.post(
            app.url_path_for(
                "Images",
                story_id="Uk",
                page=1,
            ),
            data={"text": "lorem ipsum"},
        )
        self.assertEqual(response.status_code, 200)


@app.endpoint("/stories/{story_id:str}")
class Stories(ludic.web.Endpoint[Story]):
    """Resource for accessing a Story."""

    @classmethod
    def get(cls, story_id: str) -> typing.Self:
        """Get a single story.

        Raises:
            NotFoundError: if the story doesn't exist.
        """
        story = db["stories"].get(story_id)
        if story is None:
            msg = f"story {story_id} not found"
            raise ludic.web.exceptions.NotFoundError(msg)
        return cls(**story)

    @classmethod
    def put(cls, story_id: str, data: list[PageContent]) -> typing.Self:
        """Upsert a new story."""
        pages = [
            Page(story_id=story_id, page_number=n, content=page_content)
            for n, page_content in enumerate(data)
        ]
        story = Story(id=story_id, pages=pages)
        # save to the 'database'
        db["stories"][story_id] = story
        return cls(**story)

    @typing.override
    def render(self) -> ludic.base.BaseElement:
        return layouts.Stack(
            headers.H1(str(self.attrs["id"])),
            *(Pages(**page) for page in self.attrs["pages"]),
        )


@app.endpoint("/stories")
class StoriesForm(ludic.web.Endpoint[StoryInputs]):
    """Form for generating new stories."""

    @classmethod
    def post(cls, data: ludic.web.parsers.Parser[StoryInputs]) -> Stories:
        """Upsert a new story."""
        inputs = StoryInputs(**data.validate())
        # generate story pages
        # Consider calling Pages.put for each one after generating the text
        pages = generate_pages(inputs)
        # calculate sqid
        next_id_num = 1 + Sqids.decode(db_last_story_id)[0]
        next_id = Sqids.encode([next_id_num])
        return Stories.put(next_id, pages)

    @typing.override
    def render(self) -> ludic.base.BaseElement:
        """Render the story as HTML."""
        return layouts.Box(
            forms.Form(
                forms.SelectField(
                    forms.Option("Christian", value="Christian"),
                    forms.Option("Secular", value="Secular"),
                    id="theme",
                    name="theme",
                    label="Select Theme:",
                    for_="theme",
                ),
                forms.InputField(
                    label="Main Character's Name:",
                    for_="character",
                    type="text",
                    id="character",
                    name="character",
                    required=True,
                    value="Alice",
                ),
                forms.SelectField(
                    forms.Option("Rural", value="rural"),
                    forms.Option("Urban", value="urban"),
                    forms.Option("Beach", value="beach"),
                    forms.Option("Forest", value="forest"),
                    label="Select Setting:",
                    for_="setting",
                    id="setting",
                    name="setting",
                ),
                forms.InputField(
                    label="Moral:",
                    for_="moral",
                    type="text",
                    id="moral",
                    name="moral",
                    required=True,
                    value="Honor thy mother and father",
                ),
                buttons.ButtonSuccess(
                    "Generate Story",
                    type="submit",
                    classes=["large"],
                ),
                hx_post=self.url_for(StoriesForm),
                hx_target="#story",
            ),
        )


class StorybookTest(unittest.TestCase):
    """Unit test case for the Storybook application."""

    def setUp(self) -> None:
        """Set up the test client and seed database."""
        self.client = starlette.testclient.TestClient(app)
        self.character = "Alice"
        self.data = example_story | {"character": self.character}
        self.client.post("/stories/", data=self.data)
        self.story = next(iter(db["stories"].values()))
        self.story_id = self.story["id"]

    def test_stories_post(self) -> None:
        """User can create a story."""
        response = self.client.post("/stories/", data=self.data)
        self.assertEqual(response.status_code, 200)
        self.assertIn(self.character, response.text)

    def test_stories_post_invalid_data(self) -> None:
        """Invalid POST data."""
        response = self.client.post(
            app.url_path_for("StoriesForm"),
            data={"bad": "data"},
        )
        self.assertNotEqual(response.status_code, 200)

    def test_stories_get(self) -> None:
        """User can access the story directly."""
        response = self.client.get(
            app.url_path_for("Stories", story_id=self.story_id),
        )
        self.assertEqual(response.status_code, 200)
        self.assertIn(self.character, response.text)

    def test_stories_get_nonexistent(self) -> None:
        """Returns 404 when a story is not found."""
        response = self.client.get(
            app.url_path_for("Stories", story_id="nonexistent"),
        )
        self.assertEqual(response.status_code, 404)

    def test_pages_get(self) -> None:
        """User can access one page at a time."""
        page_num = 1
        _story = self.story["pages"][page_num]
        response = self.client.get(
            app.url_path_for("Pages", story_id=self.story_id, page=page_num),
        )
        self.assertEqual(response.status_code, 200)
        self.assertIn(self.character, response.text)


if __name__ == "__main__":
    main()