Commit ·
ee2e4d6
1
Parent(s): d80baa1
Add initial project structure for AI Comic Generation
Browse files- .gitattributes +1 -0
- .gitignore +4 -0
- app.py +203 -0
- requirements.txt +11 -0
- src/__init__.py +0 -0
- src/config.py +19 -0
- src/image_generator.py +65 -0
- src/image_prompt_generator.py +50 -0
- src/llm.py +93 -0
- src/stable_diffusion.py +56 -0
- src/story_generator.py +32 -0
- static/Roboto-Regular.ttf +3 -0
- static/aivn_logo.png +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.ttf filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__
|
| 2 |
+
weights/
|
| 3 |
+
*.zip
|
| 4 |
+
.env
|
app.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import base64
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
from src.config import settings
|
| 9 |
+
from src.llm import LLMClient
|
| 10 |
+
from src.stable_diffusion import DiffusionClient
|
| 11 |
+
from src.story_generator import StoryGenerator
|
| 12 |
+
from src.image_prompt_generator import ImagePromptGenerator
|
| 13 |
+
from src.image_generator import ImageGenerator
|
| 14 |
+
|
| 15 |
+
load_dotenv()
|
| 16 |
+
logging.basicConfig(level=logging.INFO)
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
# ── Lazy-loaded singleton pipeline components ────────────────────────────────
|
| 20 |
+
llm_client: LLMClient | None = None
|
| 21 |
+
story_gen: StoryGenerator | None = None
|
| 22 |
+
prompt_gen: ImagePromptGenerator | None = None
|
| 23 |
+
img_gen: ImageGenerator | None = None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _init_pipeline():
|
| 27 |
+
"""Instantiate and load all models once on first call."""
|
| 28 |
+
global llm_client, story_gen, prompt_gen, img_gen
|
| 29 |
+
if llm_client is not None:
|
| 30 |
+
return
|
| 31 |
+
|
| 32 |
+
logger.info("Initializing comic generation pipeline...")
|
| 33 |
+
llm_client = LLMClient(
|
| 34 |
+
hf_token=settings.HF_TOKEN,
|
| 35 |
+
cache_dir=settings.CACHE_DIR,
|
| 36 |
+
)
|
| 37 |
+
llm_client.load_model()
|
| 38 |
+
|
| 39 |
+
diff_client = DiffusionClient(
|
| 40 |
+
hf_token=settings.HF_TOKEN,
|
| 41 |
+
cache_dir=settings.CACHE_DIR,
|
| 42 |
+
)
|
| 43 |
+
diff_client.load_model()
|
| 44 |
+
|
| 45 |
+
story_gen = StoryGenerator(llm_client)
|
| 46 |
+
prompt_gen = ImagePromptGenerator(llm_client)
|
| 47 |
+
img_gen = ImageGenerator(diff_client)
|
| 48 |
+
logger.info("Pipeline ready.")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# ── Core inference function ──────────────────────────────────────────────────
|
| 52 |
+
def inference(user_prompt: str):
|
| 53 |
+
"""Run the full comic generation pipeline and yield progress updates.
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
Tuple of (gallery_images, story_text, status_message).
|
| 57 |
+
"""
|
| 58 |
+
if not user_prompt or not user_prompt.strip():
|
| 59 |
+
return [], "Vui lòng nhập ý tưởng truyện.", "⚠️ Chưa nhập nội dung."
|
| 60 |
+
|
| 61 |
+
_init_pipeline()
|
| 62 |
+
|
| 63 |
+
yield [], "", "⏳ Đang tạo câu chuyện..."
|
| 64 |
+
|
| 65 |
+
raw_story = story_gen.gen_story_structured(user_prompt)
|
| 66 |
+
paragraphs = prompt_gen.parse_paragraphs(raw_story)
|
| 67 |
+
|
| 68 |
+
if not paragraphs:
|
| 69 |
+
yield [], raw_story, "⚠️ Không tách được đoạn văn. Xem raw output bên dưới."
|
| 70 |
+
return
|
| 71 |
+
|
| 72 |
+
max_scenes = min(len(paragraphs), settings.MAX_SCENES)
|
| 73 |
+
paragraphs = paragraphs[:max_scenes]
|
| 74 |
+
|
| 75 |
+
story_display = f"**Raw LLM output:**\n```\n{raw_story}\n```\n\n"
|
| 76 |
+
story_display += "**Parsed paragraphs:**\n"
|
| 77 |
+
for i, p in enumerate(paragraphs, 1):
|
| 78 |
+
story_display += f"{i}. {p}\n"
|
| 79 |
+
|
| 80 |
+
yield [], story_display, f"⏳ Đang tạo hình ảnh cho {max_scenes} cảnh..."
|
| 81 |
+
|
| 82 |
+
images = []
|
| 83 |
+
for idx, paragraph in enumerate(paragraphs):
|
| 84 |
+
visual_prompt = prompt_gen.create_visual_prompt(
|
| 85 |
+
paragraph, raw_story, settings.COMIC_STYLE
|
| 86 |
+
)
|
| 87 |
+
story_display += f"\n**Prompt {idx + 1}:** {visual_prompt}\n"
|
| 88 |
+
yield images, story_display, f"🎨 Đang vẽ cảnh {idx + 1}/{max_scenes}..."
|
| 89 |
+
|
| 90 |
+
panel = img_gen.generate_image(
|
| 91 |
+
prompt=visual_prompt,
|
| 92 |
+
paragraph=paragraph,
|
| 93 |
+
)
|
| 94 |
+
if panel is not None:
|
| 95 |
+
images.append(panel)
|
| 96 |
+
yield images, story_display, f"✅ Hoàn thành cảnh {idx + 1}/{max_scenes}"
|
| 97 |
+
|
| 98 |
+
yield images, story_display, f"🎉 Hoàn tất! Đã tạo {len(images)} panel truyện tranh."
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# ── UI helpers ───────────────────────────────────────────────────────────────
|
| 102 |
+
def _image_to_base64(image_path: str) -> str:
|
| 103 |
+
with open(image_path, "rb") as f:
|
| 104 |
+
return base64.b64encode(f.read()).decode("utf-8")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _create_header():
|
| 108 |
+
with gr.Row():
|
| 109 |
+
with gr.Column(scale=1):
|
| 110 |
+
logo_b64 = _image_to_base64("static/aivn_logo.png")
|
| 111 |
+
gr.HTML(
|
| 112 |
+
f'<img src="data:image/png;base64,{logo_b64}" '
|
| 113 |
+
'alt="Logo" style="height:120px;width:auto;margin-right:20px;margin-bottom:20px;">'
|
| 114 |
+
)
|
| 115 |
+
with gr.Column(scale=4):
|
| 116 |
+
gr.Markdown(
|
| 117 |
+
"""
|
| 118 |
+
<div style="display:flex;justify-content:space-between;align-items:center;padding:0 15px;">
|
| 119 |
+
<div>
|
| 120 |
+
<h1 style="margin-bottom:0;">🎨 AI Comic Generation Demo</h1>
|
| 121 |
+
<p style="margin-top:0.5em;color:#666;">Tạo truyện tranh từ ý tưởng bằng AI (LLM + SDXL)</p>
|
| 122 |
+
</div>
|
| 123 |
+
<div style="text-align:right;border-left:2px solid #ddd;padding-left:20px;">
|
| 124 |
+
<h3 style="margin:0;color:#2c3e50;">🚀 AIO2025 Project</h3>
|
| 125 |
+
<p style="margin:0;color:#7f8c8d;">Comic Generation with LLM & Stable Diffusion XL</p>
|
| 126 |
+
</div>
|
| 127 |
+
</div>
|
| 128 |
+
"""
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _create_footer():
|
| 133 |
+
gr.HTML(
|
| 134 |
+
"""
|
| 135 |
+
<style>
|
| 136 |
+
.sticky-footer {
|
| 137 |
+
position:fixed;bottom:0;left:0;width:100%;
|
| 138 |
+
background:white;padding:10px;
|
| 139 |
+
box-shadow:0 -2px 10px rgba(0,0,0,0.1);z-index:1000;
|
| 140 |
+
}
|
| 141 |
+
.content-wrap { padding-bottom:60px; }
|
| 142 |
+
</style>
|
| 143 |
+
<div class="sticky-footer">
|
| 144 |
+
<div style="text-align:center;font-size:14px;">
|
| 145 |
+
Created by <a href="https://vlai.work" target="_blank"
|
| 146 |
+
style="color:#007BFF;text-decoration:none;">VLAI</a> • AI VIETNAM
|
| 147 |
+
</div>
|
| 148 |
+
</div>
|
| 149 |
+
"""
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# ── App layout ───────────────────────────────────────────────────────────────
|
| 154 |
+
custom_css = """
|
| 155 |
+
.gradio-container { min-height:100vh; }
|
| 156 |
+
.content-wrap { padding-bottom:60px; }
|
| 157 |
+
.full-width-btn {
|
| 158 |
+
width:100% !important; height:50px !important;
|
| 159 |
+
font-size:18px !important; margin-top:20px !important;
|
| 160 |
+
background:linear-gradient(45deg,#FF6B6B,#4ECDC4) !important;
|
| 161 |
+
color:white !important; border:none !important;
|
| 162 |
+
}
|
| 163 |
+
.full-width-btn:hover {
|
| 164 |
+
background:linear-gradient(45deg,#FF5252,#3CB4AC) !important;
|
| 165 |
+
}
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
with gr.Blocks(css=custom_css) as demo:
|
| 169 |
+
_create_header()
|
| 170 |
+
|
| 171 |
+
with gr.Column(variant="panel"):
|
| 172 |
+
prompt_input = gr.Textbox(
|
| 173 |
+
label="💡 Tóm tắt truyện (Tiếng Việt)",
|
| 174 |
+
placeholder="Ví dụ: Một con thỏ lười biếng học được bài học về sự chăm chỉ từ một con rùa...",
|
| 175 |
+
lines=3,
|
| 176 |
+
)
|
| 177 |
+
generate_btn = gr.Button(
|
| 178 |
+
"Tạo Truyện Tranh 🎨",
|
| 179 |
+
elem_classes="full-width-btn",
|
| 180 |
+
)
|
| 181 |
+
status_box = gr.Textbox(label="Trạng thái", interactive=False)
|
| 182 |
+
|
| 183 |
+
with gr.Row(equal_height=True):
|
| 184 |
+
gallery = gr.Gallery(
|
| 185 |
+
label="🖼️ Truyện tranh",
|
| 186 |
+
columns=2,
|
| 187 |
+
object_fit="contain",
|
| 188 |
+
height="auto",
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
with gr.Accordion("📝 Chi tiết câu chuyện & prompts", open=False):
|
| 192 |
+
story_output = gr.Markdown()
|
| 193 |
+
|
| 194 |
+
generate_btn.click(
|
| 195 |
+
fn=inference,
|
| 196 |
+
inputs=prompt_input,
|
| 197 |
+
outputs=[gallery, story_output, status_box],
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
_create_footer()
|
| 201 |
+
|
| 202 |
+
if __name__ == "__main__":
|
| 203 |
+
demo.launch(allowed_paths=["static/aivn_logo.png"])
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.6.0
|
| 2 |
+
diffusers==0.32.2
|
| 3 |
+
transformers==4.50.3
|
| 4 |
+
accelerate==1.6.0
|
| 5 |
+
gradio==6.9.0
|
| 6 |
+
numpy==1.26.4
|
| 7 |
+
pillow
|
| 8 |
+
pydantic-settings
|
| 9 |
+
python-dotenv
|
| 10 |
+
sentencepiece
|
| 11 |
+
bitsandbytes>=0.46.1
|
src/__init__.py
ADDED
|
File without changes
|
src/config.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
from pydantic_settings import BaseSettings
|
| 4 |
+
|
| 5 |
+
load_dotenv()
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Settings(BaseSettings):
|
| 9 |
+
HF_TOKEN: str = os.getenv("HF_TOKEN", "")
|
| 10 |
+
CACHE_DIR: str = os.getenv("CACHE_DIR", "./cache")
|
| 11 |
+
MAX_SCENES: int = 4
|
| 12 |
+
COMIC_STYLE: str = (
|
| 13 |
+
"whimsical watercolor children's book illustration, "
|
| 14 |
+
"hand-drawn, soft pencil outlines, pastel colors, "
|
| 15 |
+
"cozy atmosphere, high quality, magical lighting"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
settings = Settings()
|
src/image_generator.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import textwrap
|
| 3 |
+
import logging
|
| 4 |
+
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
| 5 |
+
from src.stable_diffusion import DiffusionClient
|
| 6 |
+
|
| 7 |
+
logging.basicConfig(level=logging.INFO)
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
FONT_PATH = os.path.join(os.path.dirname(__file__), "..", "static", "Roboto-Regular.ttf")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ImageGenerator:
|
| 14 |
+
def __init__(self, diffusion_client: DiffusionClient):
|
| 15 |
+
self.diffusion_client = diffusion_client
|
| 16 |
+
|
| 17 |
+
def add_caption_box(self, image: Image.Image, text: str) -> Image.Image:
|
| 18 |
+
img_with_border = ImageOps.expand(image, border=15, fill="black")
|
| 19 |
+
img_copy = img_with_border.convert("RGBA")
|
| 20 |
+
overlay = Image.new("RGBA", img_copy.size, (255, 255, 255, 0))
|
| 21 |
+
draw = ImageDraw.Draw(overlay)
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
font = ImageFont.truetype(FONT_PATH, 32)
|
| 25 |
+
except Exception:
|
| 26 |
+
font = ImageFont.load_default()
|
| 27 |
+
|
| 28 |
+
wrapped_text = textwrap.wrap(text, width=55)
|
| 29 |
+
line_height = 40
|
| 30 |
+
text_total_height = len(wrapped_text) * line_height
|
| 31 |
+
|
| 32 |
+
box_bottom = img_copy.size[1] - 30
|
| 33 |
+
box_top = box_bottom - text_total_height - 30
|
| 34 |
+
draw.rectangle(
|
| 35 |
+
[(30, box_top), (img_copy.size[0] - 30, box_bottom)],
|
| 36 |
+
fill=(255, 255, 255, 235),
|
| 37 |
+
outline=(0, 0, 0, 255),
|
| 38 |
+
width=6,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
y_text = box_top + 15
|
| 42 |
+
for line in wrapped_text:
|
| 43 |
+
draw.text((45, y_text), line, font=font, fill="black")
|
| 44 |
+
y_text += line_height
|
| 45 |
+
|
| 46 |
+
return Image.alpha_composite(img_copy, overlay).convert("RGB")
|
| 47 |
+
|
| 48 |
+
def generate_image(
|
| 49 |
+
self,
|
| 50 |
+
prompt: str,
|
| 51 |
+
paragraph: str,
|
| 52 |
+
num_inference_steps: int = 5,
|
| 53 |
+
guidance_scale: float = 2.0,
|
| 54 |
+
size: int = 1024,
|
| 55 |
+
) -> Image.Image | None:
|
| 56 |
+
raw_img = self.diffusion_client.gen_image(
|
| 57 |
+
prompt=prompt,
|
| 58 |
+
num_inference_steps=num_inference_steps,
|
| 59 |
+
guidance_scale=guidance_scale,
|
| 60 |
+
width=size,
|
| 61 |
+
height=size,
|
| 62 |
+
)
|
| 63 |
+
if raw_img is not None:
|
| 64 |
+
return self.add_caption_box(raw_img, paragraph)
|
| 65 |
+
return None
|
src/image_prompt_generator.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import logging
|
| 3 |
+
from src.llm import LLMClient
|
| 4 |
+
|
| 5 |
+
logging.basicConfig(level=logging.INFO)
|
| 6 |
+
logger = logging.getLogger(__name__)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ImagePromptGenerator:
|
| 10 |
+
def __init__(self, llm_client: LLMClient):
|
| 11 |
+
self.llm_client = llm_client
|
| 12 |
+
|
| 13 |
+
def parse_paragraphs(self, raw_text: str) -> list[str]:
|
| 14 |
+
paragraphs = []
|
| 15 |
+
pattern = r"<\|paragraph\|>(.*?)(?=<\|paragraph\|>|<\|eos\|>|$)"
|
| 16 |
+
for match in re.finditer(pattern, raw_text, re.DOTALL):
|
| 17 |
+
content = match.group(1).strip()
|
| 18 |
+
if content:
|
| 19 |
+
paragraphs.append(content)
|
| 20 |
+
return paragraphs
|
| 21 |
+
|
| 22 |
+
def create_visual_prompt(
|
| 23 |
+
self,
|
| 24 |
+
paragraph: str,
|
| 25 |
+
full_story: str,
|
| 26 |
+
style: str = (
|
| 27 |
+
"whimsical fable book illustration, highly detailed, "
|
| 28 |
+
"vibrant colors, fantasy art style"
|
| 29 |
+
),
|
| 30 |
+
) -> str:
|
| 31 |
+
if self.llm_client is None:
|
| 32 |
+
logger.warning("LLM Client does not exist. Return fallback prompt.")
|
| 33 |
+
return f"{paragraph}, {style}"
|
| 34 |
+
|
| 35 |
+
translation_prompt = f"""You are an expert art director. Given the full context of a Vietnamese story, translate the specific paragraph into a highly short descriptive English image prompt.
|
| 36 |
+
Maintain visual consistency of characters, objects, and environments based on the overall story.
|
| 37 |
+
Focus only on the visual elements (characters, actions, environment) of the specific paragraph.
|
| 38 |
+
Do NOT include any explanations or conversational text. Return ONLY the English translation, under 50 words.
|
| 39 |
+
|
| 40 |
+
Full Story Context: "{full_story}"
|
| 41 |
+
|
| 42 |
+
Specific Paragraph to visualize: "{paragraph}"
|
| 43 |
+
|
| 44 |
+
English Image Prompt:"""
|
| 45 |
+
|
| 46 |
+
english_translation = self.llm_client.generate(
|
| 47 |
+
translation_prompt, max_new_tokens=100
|
| 48 |
+
)
|
| 49 |
+
english_translation = english_translation.strip(' "\'\n')
|
| 50 |
+
return f"{english_translation}, {style}"
|
src/llm.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import (
|
| 3 |
+
AutoTokenizer,
|
| 4 |
+
AutoModelForCausalLM,
|
| 5 |
+
BitsAndBytesConfig,
|
| 6 |
+
pipeline,
|
| 7 |
+
)
|
| 8 |
+
import logging
|
| 9 |
+
|
| 10 |
+
logging.basicConfig(level=logging.INFO)
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class LLMClient:
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
model_id: str = "meta-llama/Meta-Llama-3-8B-Instruct",
|
| 18 |
+
hf_token: str | None = None,
|
| 19 |
+
cache_dir: str = "./cache",
|
| 20 |
+
):
|
| 21 |
+
self.model_id = model_id
|
| 22 |
+
self.hf_token = hf_token
|
| 23 |
+
self.cache_dir = cache_dir
|
| 24 |
+
self.model = None
|
| 25 |
+
self.generator = None
|
| 26 |
+
self.tokenizer = None
|
| 27 |
+
|
| 28 |
+
def load_model(self):
|
| 29 |
+
if self.model is not None:
|
| 30 |
+
logger.info("LLM %s already loaded. Skipping.", self.model_id)
|
| 31 |
+
return
|
| 32 |
+
|
| 33 |
+
logger.info("Loading LLM %s...", self.model_id)
|
| 34 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 35 |
+
self.model_id, token=self.hf_token, cache_dir=self.cache_dir
|
| 36 |
+
)
|
| 37 |
+
if self.tokenizer.pad_token is None:
|
| 38 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 39 |
+
|
| 40 |
+
llama3_template = (
|
| 41 |
+
"{% set loop_messages = messages %}"
|
| 42 |
+
"{% for message in loop_messages %}"
|
| 43 |
+
"{% if message['role'] == 'system' %}"
|
| 44 |
+
"{{ '<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n' "
|
| 45 |
+
"+ message['content'] + '<|eot_id|>' }}"
|
| 46 |
+
"{% elif message['role'] == 'user' %}"
|
| 47 |
+
"{{ '<|start_header_id|>user<|end_header_id|>\n\n' "
|
| 48 |
+
"+ message['content'] + '<|eot_id|>' }}"
|
| 49 |
+
"{% elif message['role'] == 'assistant' %}"
|
| 50 |
+
"{{ '<|start_header_id|>assistant<|end_header_id|>\n\n' "
|
| 51 |
+
"+ message['content'] + '<|eot_id|>' }}"
|
| 52 |
+
"{% endif %}{% endfor %}"
|
| 53 |
+
"{% if add_generation_prompt %}"
|
| 54 |
+
"{{ '<|start_header_id|>assistant<|end_header_id|>\n\n' }}"
|
| 55 |
+
"{% endif %}"
|
| 56 |
+
)
|
| 57 |
+
self.tokenizer.chat_template = llama3_template
|
| 58 |
+
|
| 59 |
+
bnb_config = BitsAndBytesConfig(
|
| 60 |
+
load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16
|
| 61 |
+
)
|
| 62 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 63 |
+
self.model_id,
|
| 64 |
+
device_map="auto",
|
| 65 |
+
quantization_config=bnb_config,
|
| 66 |
+
token=self.hf_token,
|
| 67 |
+
cache_dir=self.cache_dir,
|
| 68 |
+
)
|
| 69 |
+
self.generator = pipeline(
|
| 70 |
+
"text-generation", model=self.model, tokenizer=self.tokenizer
|
| 71 |
+
)
|
| 72 |
+
logger.info("LLM loaded successfully.")
|
| 73 |
+
|
| 74 |
+
def generate(self, prompt: str, max_new_tokens: int = 512) -> str:
|
| 75 |
+
if self.generator is None:
|
| 76 |
+
self.load_model()
|
| 77 |
+
|
| 78 |
+
messages = [
|
| 79 |
+
{"role": "system", "content": "You are a helpful and precise assistant."},
|
| 80 |
+
{"role": "user", "content": prompt},
|
| 81 |
+
]
|
| 82 |
+
prompt_text = self.tokenizer.apply_chat_template(
|
| 83 |
+
messages, tokenize=False, add_generation_prompt=True
|
| 84 |
+
)
|
| 85 |
+
outputs = self.generator(
|
| 86 |
+
prompt_text,
|
| 87 |
+
max_new_tokens=max_new_tokens,
|
| 88 |
+
return_full_text=False,
|
| 89 |
+
temperature=0.7,
|
| 90 |
+
do_sample=True,
|
| 91 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
| 92 |
+
)
|
| 93 |
+
return outputs[0]["generated_text"].strip()
|
src/stable_diffusion.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import logging
|
| 3 |
+
from diffusers import StableDiffusionXLPipeline
|
| 4 |
+
|
| 5 |
+
logging.basicConfig(level=logging.INFO)
|
| 6 |
+
logger = logging.getLogger(__name__)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class DiffusionClient:
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
huggingface_path: str = "Lykon/dreamshaper-xl-v2-turbo",
|
| 13 |
+
hf_token: str | None = None,
|
| 14 |
+
cache_dir: str | None = "./cache",
|
| 15 |
+
):
|
| 16 |
+
self.huggingface_path = huggingface_path
|
| 17 |
+
self.hf_token = hf_token
|
| 18 |
+
self.cache_dir = cache_dir
|
| 19 |
+
self.pipeline = None
|
| 20 |
+
|
| 21 |
+
def load_model(self):
|
| 22 |
+
logger.info("Loading SDXL model...")
|
| 23 |
+
self.pipeline = StableDiffusionXLPipeline.from_pretrained(
|
| 24 |
+
self.huggingface_path,
|
| 25 |
+
torch_dtype=torch.float16,
|
| 26 |
+
variant="fp16",
|
| 27 |
+
use_safetensors=True,
|
| 28 |
+
token=self.hf_token,
|
| 29 |
+
cache_dir=self.cache_dir,
|
| 30 |
+
)
|
| 31 |
+
self.pipeline.enable_model_cpu_offload()
|
| 32 |
+
self.pipeline.enable_vae_slicing()
|
| 33 |
+
self.pipeline.enable_vae_tiling()
|
| 34 |
+
logger.info("Loaded SDXL model %s successfully.", self.huggingface_path)
|
| 35 |
+
|
| 36 |
+
def gen_image(
|
| 37 |
+
self,
|
| 38 |
+
prompt: str,
|
| 39 |
+
negative_prompt: str = "",
|
| 40 |
+
num_inference_steps: int = 5,
|
| 41 |
+
guidance_scale: float = 2.0,
|
| 42 |
+
width: int = 1024,
|
| 43 |
+
height: int = 1024,
|
| 44 |
+
):
|
| 45 |
+
if self.pipeline is None:
|
| 46 |
+
self.load_model()
|
| 47 |
+
|
| 48 |
+
image = self.pipeline(
|
| 49 |
+
prompt=prompt,
|
| 50 |
+
negative_prompt=negative_prompt,
|
| 51 |
+
num_inference_steps=num_inference_steps,
|
| 52 |
+
guidance_scale=guidance_scale,
|
| 53 |
+
width=width,
|
| 54 |
+
height=height,
|
| 55 |
+
).images[0]
|
| 56 |
+
return image
|
src/story_generator.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from src.llm import LLMClient
|
| 3 |
+
|
| 4 |
+
logging.basicConfig(level=logging.INFO)
|
| 5 |
+
logger = logging.getLogger(__name__)
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class StoryGenerator:
|
| 9 |
+
def __init__(self, llm_client: LLMClient):
|
| 10 |
+
self.model = llm_client
|
| 11 |
+
|
| 12 |
+
def load(self):
|
| 13 |
+
logger.info("Initializing Story Generator...")
|
| 14 |
+
self.model.load_model()
|
| 15 |
+
|
| 16 |
+
def create_story_prompt(self, user_story: str) -> str:
|
| 17 |
+
return f"""Hãy mở rộng đoạn tóm tắt dưới đây thành một câu chuyện ngụ ngôn.
|
| 18 |
+
Tóm tắt câu chuyện:
|
| 19 |
+
{user_story}
|
| 20 |
+
|
| 21 |
+
Bạn phải định dạng đầu ra chính xác như sau, nội dung từng đoạn phải bắt đầu bằng một thẻ <|paragraph|>:
|
| 22 |
+
<|paragraph|> [Nội dung đoạn 1] <|paragraph|> [Nội dung đoạn 2]
|
| 23 |
+
|
| 24 |
+
Chú ý:
|
| 25 |
+
- Không sinh thêm thẻ nào ngoài các thẻ <|paragraph|> đã được quy định.
|
| 26 |
+
- Phong cách kể chuyện ngụ ngôn, không cần sinh tên cụ thể cho nhân vật.
|
| 27 |
+
- Nội dung sinh ra là Tiếng Việt, giới hạn dưới 20 từ mỗi đoạn.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def gen_story_structured(self, user_story: str, max_new_tokens: int = 400) -> str:
|
| 31 |
+
final_prompt = self.create_story_prompt(user_story)
|
| 32 |
+
return self.model.generate(final_prompt, max_new_tokens=max_new_tokens)
|
static/Roboto-Regular.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d7598e12c5dbef095ff8272cfc55da0250bd07fbdecbac8a530b9b277872a134
|
| 3 |
+
size 488584
|
static/aivn_logo.png
ADDED
|