Spaces:
Runtime error
Runtime error
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) |