File size: 11,880 Bytes
6027a38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler
from sqlmodel import Field, Session, SQLModel, create_engine, select
from typing import Optional, List, Tuple
import hashlib
from datetime import datetime
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from reportlab.platypus import SimpleDocTemplate, Paragraph, Image, PageBreak, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY
from PIL import Image as PILImage
import os

# ์บ๋ฆญํ„ฐ ์ผ๊ด€์„ฑ์„ ์œ„ํ•œ ๊ณ ์ • ์†์„ฑ ์ถ”๊ฐ€ (ํ•œ๊ตญ์–ด)
CHARACTER_DESCRIPTION = "young korean man with blue hoodie"

# ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋ชจ๋ธ
class Story(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    prompt: str
    content: str
    created_at: datetime = Field(default_factory=datetime.now)

class ImageCache(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    prompt_hash: str = Field(index=True)
    image_path: str
    created_at: datetime = Field(default_factory=datetime.now)

# ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ดˆ๊ธฐํ™”
engine = create_engine("sqlite:///storybook.db")
SQLModel.metadata.create_all(engine)

# ๋ชจ๋ธ ์ดˆ๊ธฐํ™”
print("๋ชจ๋ธ ๋กœ๋”ฉ ์ค‘...")
device = "cuda" if torch.cuda.is_available() else "cpu"

# LLM ๋ชจ๋ธ
llm_model_name = "Bllossom/llama-3.2-Korean-Bllossom-AICA-5B"
tokenizer = AutoTokenizer.from_pretrained(llm_model_name)
llm_model = AutoModelForCausalLM.from_pretrained(
    llm_model_name,
    torch_dtype=torch.float16 if device == "cuda" else torch.float32,
    device_map="auto"
)

# Stable Diffusion ๋ชจ๋ธ
sd_model_name = "Lykon/DreamShaper"
sd_pipe = StableDiffusionPipeline.from_pretrained(
    sd_model_name,
    torch_dtype=torch.float16 if device == "cuda" else torch.float32,
    use_safetensors=False
)
sd_pipe = sd_pipe.to(device)

# ๋ชจ๋ธ ๋กœ๋“œ ํ›„ ์Šค์ผ€์ค„๋Ÿฌ ๋ณ€๊ฒฝ
sd_pipe.scheduler = DPMSolverMultistepScheduler.from_config(
    sd_pipe.scheduler.config,
    use_karras_sigmas=True,  # Karras schedule
    algorithm_type="dpmsolver++"
)

# ์ด๋ฏธ์ง€ ์ €์žฅ ๋””๋ ‰ํ† ๋ฆฌ
os.makedirs("generated_images", exist_ok=True)


def generate_story(prompt: str) -> Tuple[str, List[str]]:
    """ํ”„๋กฌํ”„ํŠธ๋กœ๋ถ€ํ„ฐ ์Šคํ† ๋ฆฌ ์ƒ์„ฑ"""
    system_prompt = f"""๋‹น์‹ ์€ ๋›ฐ์–ด๋‚œ ์Šคํ† ๋ฆฌํ…”๋Ÿฌ์ž…๋‹ˆ๋‹ค.
๋‹ค์Œ ์ฃผ์ œ๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ, 5๊ฐœ์˜ ๋ฌธ๋‹จ์œผ๋กœ ๊ตฌ์„ฑ๋œ ํฅ๋ฏธ๋กœ์šด ์ด์•ผ๊ธฐ๋ฅผ ์ž‘์„ฑํ•˜์„ธ์š”.

๊ทœ์น™:
- ์ฃผ์ธ๊ณต์€ '์ฒญ๋…„' ๋˜๋Š” '๊ทธ'๋กœ๋งŒ ์ง€์นญํ•˜์„ธ์š” (์ด๋ฆ„ ์‚ฌ์šฉ ๊ธˆ์ง€)
- ์ฃผ์ธ๊ณต์€ ์•ˆ๊ฒฝ์„ ์“ด 20๋Œ€ ์ฒญ๋…„์ž…๋‹ˆ๋‹ค
- ๊ฐ ๋ฌธ๋‹จ์€ 2~4๊ฐœ์˜ ๋ฌธ์žฅ์œผ๋กœ ๊ตฌ์„ฑ
- ์‹œ๊ฐ์ ์œผ๋กœ ํ‘œํ˜„ ๊ฐ€๋Šฅํ•œ ๊ตฌ์ฒด์ ์ธ ์žฅ๋ฉด ๋ฌ˜์‚ฌ ํฌํ•จ
- ์ˆœ์ˆ˜ ํ•œ๊ตญ์–ด๋งŒ ์‚ฌ์šฉ
- ๊ฐ ๋ฌธ๋‹จ๋งˆ๋‹ค ๋ช…ํ™•ํ•œ ์žฅ์†Œ์™€ ํ–‰๋™ ๋ฌ˜์‚ฌ

์ฃผ์ œ: {prompt}

์ด์•ผ๊ธฐ:"""
    
    inputs = tokenizer(system_prompt, return_tensors="pt").to(device)
    
    with torch.no_grad():
        outputs = llm_model.generate(
            **inputs,
            max_new_tokens=1000,
            temperature=0.7,
            do_sample=True,
            top_p=0.92,
            repetition_penalty=1.1,
        )
    
    story = tokenizer.decode(outputs[0], skip_special_tokens=True)
    story = story.replace(system_prompt, "").strip()
    
    # ๋ฌธ๋‹จ ๋ถ„๋ฆฌ
    paragraphs = []
    raw_paragraphs = story.split("\n\n")
    for p in raw_paragraphs:
        p = p.strip()
        if p and len(p) > 20:
            paragraphs.append(p)
    
    paragraphs = paragraphs[:5]
    
    # DB ์ €์žฅ
    with Session(engine) as session:
        db_story = Story(prompt=prompt, content="\n\n".join(paragraphs))
        session.add(db_story)
        session.commit()
    
    return "\n\n".join(paragraphs), paragraphs


def analyze_text_for_english_scene(text: str, paragraph_num: int = 1) -> str:
    """ํ…์ŠคํŠธ๋ฅผ ๋ถ„์„ํ•˜์—ฌ ์˜์–ด ์”ฌ ์ถ”์ถœ (๊ธฐ๋ณธ 10๊ฐœ ํ‚ค์›Œ๋“œ)"""
    
    # ๋””๋ฒ„๊น…์šฉ ์ถœ๋ ฅ
    print(f"[{paragraph_num}] ํ…์ŠคํŠธ ๋ถ„์„ ์ค‘: {text[:60]}...")
    
    # ํ•ต์‹ฌ ํ‚ค์›Œ๋“œ 10๊ฐœ๋งŒ ์ฒ˜๋ฆฌ
    # 1. ์นดํŽ˜ + ๋…ธํŠธ๋ถ/์ปดํ“จํ„ฐ
    if "์นดํŽ˜" in text and ("๋…ธํŠธ๋ถ" in text or "์ปดํ“จํ„ฐ" in text):
        return "working on laptop in coffee shop"
    
    # 2. ์นดํŽ˜ (์ผ๋ฐ˜)
    elif "์นดํŽ˜" in text:
        return "in a coffee shop"
    
    # 3. ํ”„๋กœ๊ทธ๋ž˜๋ฐ/์ฝ”๋”ฉ
    elif "ํ”„๋กœ๊ทธ๋ž˜๋ฐ" in text or "์ฝ”๋”ฉ" in text or "์ฝ”๋“œ" in text:
        return "coding on laptop"
    
    # 4. ํšŒ์˜/๋ฏธํŒ…
    elif "ํšŒ์˜" in text or "๋ฏธํŒ…" in text:
        return "in a meeting"
    
    # 5. ๋ฐœํ‘œ/ํ”„๋ ˆ์  ํ…Œ์ด์…˜
    elif "๋ฐœํ‘œ" in text or "ํ”„๋ ˆ์  ํ…Œ์ด์…˜" in text:
        return "giving presentation"
    
    # 6. ๋™๋ฃŒ/ํŒ€
    elif "๋™๋ฃŒ" in text or "ํŒ€" in text:
        return "with team members"
    
    # 7. ์„ฑ๊ณต/์ถ•ํ•˜
    elif "์„ฑ๊ณต" in text or "์ถ•ํ•˜" in text:
        return "celebrating success"
    
    # 8. ๊ณ„ํš
    elif "๊ณ„ํš" in text:
        return "planning"
    
    # 9. ์‚ฌ๋ฌด์‹ค
    elif "์‚ฌ๋ฌด์‹ค" in text:
        return "in office"
    
    # 10. ํˆฌ์ž/ํˆฌ์ž์ž
    elif "ํˆฌ์ž" in text:
        return "meeting investors"
    
    # ๊ธฐ๋ณธ๊ฐ’ (๋ฌธ๋‹จ๋ณ„)
    defaults = {
        1: "young entrepreneur working",
        2: "developing project",
        3: "collaborating with others",
        4: "business presentation",
        5: "successful achievement"
    }
    
    return defaults.get(paragraph_num, "at work")

    
def generate_image(text: str, paragraph_num: int = 1) -> str:
    """ํ…์ŠคํŠธ๋กœ๋ถ€ํ„ฐ ์ด๋ฏธ์ง€ ์ƒ์„ฑ"""
    # ํ”„๋กฌํ”„ํŠธ ํ•ด์‹œ ์ƒ์„ฑ
    prompt_hash = hashlib.md5(text.encode()).hexdigest()
    
    # ์บ์‹œ ํ™•์ธ
    with Session(engine) as session:
        cached = session.exec(
            select(ImageCache).where(ImageCache.prompt_hash == prompt_hash)
        ).first()
        
        if cached:
            return cached.image_path
    
    # ์”ฌ ์ถ”์ถœ
    print(f"\n[{paragraph_num}/5] ์ด๋ฏธ์ง€ ์ƒ์„ฑ ์ค‘...")
    scene = analyze_text_for_english_scene(text)
    
    # ์ตœ์ข… ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ 
    final_prompt = f"{CHARACTER_DESCRIPTION} {scene}"
    
    
    print("์ตœ์ข… ํ”„๋กฌํ”„ํŠธ: ", final_prompt)
    print(f"ํ”„๋กฌํ”„ํŠธ ๊ธธ์ด: {len(final_prompt)} ๊ธ€์ž")
    
    # ๋„ค๊ฑฐํ‹ฐ๋ธŒ ํ”„๋กฌํ”„ํŠธ
    negative_prompt = "realistic, photo, multiple people, crowd"
    
    # Seed ๊ณ ์ •
    base_seed = 396135060
    # Seed ๋ฏธ์„ธ ๋ณ€ํ™”
    seed = base_seed + (paragraph_num * 10)  # 10, 20, 30, 40, 50
    # Seed ๋‹ค๋ณ€ํ™”
    #text_hash = int(hashlib.md5(text.encode()).hexdigest()[:8], 16)
    #seed = base_seed + (text_hash % 1000)
    generator = torch.Generator(device=device).manual_seed(seed)
    #generator = torch.Generator(device=device).manual_seed(
    #    torch.randint(0, 100000, (1,)).item()
    #)
    
    # ์ด๋ฏธ์ง€ ์ƒ์„ฑ
    with torch.no_grad():
        image = sd_pipe(
            prompt=final_prompt,
            negative_prompt=negative_prompt,
            num_inference_steps=20,
            guidance_scale=6.0,
            height=512,
            width=512,
            generator=generator,
            safety_checker=None,
            requires_safety_checker=False
        ).images[0]
    
    # ์ด๋ฏธ์ง€ ์ €์žฅ
    image_path = f"generated_images/{prompt_hash}.png"
    image.save(image_path)
    
    # ์บ์‹œ ์ €์žฅ
    with Session(engine) as session:
        cache_entry = ImageCache(prompt_hash=prompt_hash, image_path=image_path)
        session.add(cache_entry)
        session.commit()
    
    return image_path

def create_pdf(story_text: str, image_paths: List[str], output_path: str = "storybook.pdf"):
    """์Šคํ† ๋ฆฌ์™€ ์ด๋ฏธ์ง€๋กœ PDF ์ƒ์„ฑ"""
    doc = SimpleDocTemplate(output_path, pagesize=A4)
    story = []

    font_path = "malgun.ttf"
    pdfmetrics.registerFont(TTFont('๋ง‘์€๊ณ ๋”•', font_path))

    # ์Šคํƒ€์ผ ์„ค์ •
    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        'CustomTitle',
        parent=styles['Heading1'],
        fontName="๋ง‘์€๊ณ ๋”•",
        fontSize=24,
        textColor='black',
        alignment=TA_CENTER,
        spaceAfter=30
    )

    text_style = ParagraphStyle(
        'CustomText',
        parent=styles['Normal'],
        fontName="๋ง‘์€๊ณ ๋”•",
        fontSize=12,
        leading=18,
        alignment=TA_JUSTIFY,
        spaceAfter=20
    )

    story.append(Paragraph("AI ์Šคํ† ๋ฆฌ๋ถ", title_style))
    story.append(Spacer(1, 1*cm))

    paragraphs = story_text.strip().split("\n\n")
    for i, para in enumerate(paragraphs):
        story.append(Paragraph(para.strip(), text_style))
        
        if i < len(image_paths) and os.path.exists(image_paths[i]):
            img = Image(image_paths[i], width=15*cm, height=10*cm)
            story.append(img)
            story.append(Spacer(1, 1*cm))

        if i < len(paragraphs) - 1:
            story.append(PageBreak())

    doc.build(story)
    return output_path

# Gradio ์ธํ„ฐํŽ˜์ด์Šค
def process_story(prompt: str):
    """์Šคํ† ๋ฆฌ ์ƒ์„ฑ ์ฒ˜๋ฆฌ"""
    story, paragraphs = generate_story(prompt)
    return story, gr.update(visible=True), paragraphs

def generate_images_batch(paragraphs: List[str]):
    """๋ฐฐ์น˜๋กœ ์ด๋ฏธ์ง€ ์ƒ์„ฑ (์ง„ํ–‰๋ฅ  ํ‘œ์‹œ)"""
    from tqdm import tqdm
    
    image_paths = []
    for i, para in tqdm(enumerate(paragraphs), total=len(paragraphs), desc="์ด๋ฏธ์ง€ ์ƒ์„ฑ"):
        img_path = generate_image(para, paragraph_num=i+1)
        image_paths.append(img_path)
        
        if device == "cuda":
            torch.cuda.empty_cache()
    
    return image_paths

def create_storybook(story_text: str, paragraphs: List[str]):
    """์Šคํ† ๋ฆฌ๋ถ PDF ์ƒ์„ฑ"""
    # ์ด๋ฏธ์ง€ ์ƒ์„ฑ
    image_paths = generate_images_batch(paragraphs)
    
    # PDF ์ƒ์„ฑ
    pdf_path = create_pdf(story_text, image_paths)
    
    # ์ด๋ฏธ์ง€ ๊ฐค๋Ÿฌ๋ฆฌ์šฉ ๋ฐ์ดํ„ฐ
    images = [PILImage.open(path) for path in image_paths]
    
    return images, pdf_path

# Gradio UI
with gr.Blocks(title="AI ์Šคํ† ๋ฆฌ๋ถ ์ €์ž‘ ๋„๊ตฌ") as app:
    gr.Markdown("# AI ์Šคํ† ๋ฆฌ๋ถ ์ €์ž‘ ๋„๊ตฌ")
    
    with gr.Row():
        with gr.Column():
            prompt_input = gr.Textbox(
                label="์Šคํ† ๋ฆฌ ์ฃผ์ œ ์ž…๋ ฅ",
                placeholder="์˜ˆ: ์Šคํƒ€ํŠธ์—… ์ฐฝ์—… ์„ฑ๊ณต ์Šคํ† ๋ฆฌ",
                lines=2
            )
            generate_btn = gr.Button("์Šคํ† ๋ฆฌ ์ƒ์„ฑ", variant="primary")
            
            story_output = gr.Textbox(
                label="์ƒ์„ฑ๋œ ์Šคํ† ๋ฆฌ",
                lines=15,
                interactive=True
            )
            
            create_book_btn = gr.Button(
                "์Šคํ† ๋ฆฌ๋ถ ์ƒ์„ฑ (์ด๋ฏธ์ง€ + PDF)",
                variant="secondary",
                visible=False
            )
        
        with gr.Column():
            image_gallery = gr.Gallery(
                label="์ƒ์„ฑ๋œ ์ด๋ฏธ์ง€",
                show_label=True,
                elem_id="gallery",
                columns=2,
                rows=3,
                height="auto"
            )
            
            pdf_output = gr.File(
                label="PDF ๋‹ค์šด๋กœ๋“œ",
                visible=True
            )
    
    # ์ƒํƒœ ์ €์žฅ
    paragraphs_state = gr.State([])
    
    # ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ
    generate_btn.click(
        fn=process_story,
        inputs=[prompt_input],
        outputs=[story_output, create_book_btn, paragraphs_state]
    )
    
    create_book_btn.click(
        fn=create_storybook,
        inputs=[story_output, paragraphs_state],
        outputs=[image_gallery, pdf_output]
    )

if __name__ == "__main__":
    app.launch(share=True)