Spaces:
Running
Running
v5: 1 image per full page — 32 Pollinations calls for 32 pages, no 128 panels, sequential+retry
Browse files12345678910112 unmodified lines1415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365import gradio as grimport osimport jsonimport reimport timeimport base64import requestsimport urllib.parsefrom PIL import Image, ImageDraw, ImageFontfrom io import BytesIOfrom huggingface_hub import InferenceClient2 unmodified linesHF_TOKEN = os.environ.get('HF_TOKEN', '')# ── FONTS ─────────────────────────────────────────────────────────────────────BOLD = ['/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf','/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf','/usr/share/fonts/truetype/freefont/FreeSansBold.ttf','/usr/share/fonts/truetype/ubuntu/Ubuntu-B.ttf']REGULAR = ['/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf','/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf','/usr/share/fonts/truetype/freefont/FreeSans.ttf','/usr/share/fonts/truetype/ubuntu/Ubuntu-R.ttf']def font(paths, size):for p in paths:try: return ImageFont.truetype(p, size)except: passtry: return ImageFont.load_default(size=size)except: return ImageFont.load_default()def wrap(text, fnt, max_w, draw):words = str(text).split()lines, cur = [], ''for w in words:test = (cur + ' ' + w).strip()if draw.textlength(test, font=fnt) <= max_w:cur = testelse:if cur: lines.append(cur)cur = wif cur: lines.append(cur)return lines or [str(text)[:40]]# ── SPEECH BUBBLE ─────────────────────────────────────────────────────────────def draw_bubble(draw, img_w, img_h, text, char_name, idx):if not text or not text.strip():returnf_char = font(BOLD, 22)f_text = font(REGULAR, 24)pad = 20max_w = min(img_w - 100, 560)lines = wrap(text[:100], f_text, max_w, draw)char_w = int(draw.textlength(char_name + ':', font=f_char)) if char_name else 0text_w = max((int(draw.textlength(l, font=f_text)) for l in lines), default=80)bw = max(text_w, char_w) + pad * 2 + 10line_h = 30bh = len(lines) * line_h + pad * 2 + (28 if char_name else 0)margin = 24bx = margin if idx % 2 == 0 else img_w - bw - marginby = margin + idx * (bh + 18)if by + bh > img_h - 80: by = marginbx2, by2 = bx + bw, by + bh# Shadowdraw.rounded_rectangle([bx+4, by+4, bx2+4, by2+4], radius=18, fill=(0,0,0))# Filldraw.rounded_rectangle([bx, by, bx2, by2], radius=18, fill=(255,255,255), outline=(5,5,5), width=3)# Tailtx = bx + bw//2draw.polygon([(tx-12, by2),(tx+12, by2),(tx, by2+20)], fill=(255,255,255))draw.line([(tx-12,by2),(tx,by2+20)], fill=(5,5,5), width=3)draw.line([(tx+12,by2),(tx,by2+20)], fill=(5,5,5), width=3)ty = by + pad//2if char_name:draw.text((bx+pad, ty), char_name+':', font=f_char, fill=(20,20,200))ty += 28for line in lines:draw.text((bx+pad, ty), line, font=f_text, fill=(10,10,10))ty += line_hdef apply_bubbles(img, dialogues):out = img.copy().convert('RGBA')ov = Image.new('RGBA', out.size, (0,0,0,0))dr = ImageDraw.Draw(ov)for i, dlg in enumerate(dialogues[:2]):draw_bubble(dr, out.width, out.height,str(dlg.get('text','')), str(dlg.get('character','')), i)return Image.alpha_composite(out, ov).convert('RGB')def add_border(img, panel_num, page_num):img = img.copy().convert('RGB')dr = ImageDraw.Draw(img)w, h = img.sizedr.rectangle([0,0,w-1,h-1], outline=(0,0,0), width=5)badge = str(page_num)+'-'+str(panel_num)f = font(BOLD, 16)bw = int(dr.textlength(badge, font=f))+12dr.rectangle([w-bw-4, h-26, w-4, h-4], fill=(0,0,0))dr.text((w-bw//2-4, h-15), badge, font=f, fill=(255,255,255), anchor='mm')return img# ── PAGE COMPOSER ─────────────────────────────────────────────────────────────def compose_page(panels, page_num, total_pages, title):PW, PH = 1240, 1754HH, FH, G = 58, 42, 10page = Image.new('RGB', (PW, PH), (255,255,255))dr = ImageDraw.Draw(page)dr.rectangle([0,0,PW,HH], fill=(15,15,15))dr.text((PW//2, HH//2), title.upper()[:60], font=font(BOLD,28), fill=(255,255,255), anchor='mm')fy = PH-FHdr.rectangle([0,fy,PW,PH], fill=(220,220,220))dr.text((PW//2, fy+FH//2), str(page_num)+' / '+str(total_pages), font=font(REGULAR,20), fill=(60,60,60), anchor='mm')cy0 = HH+G; cy1 = fy-Gcx0 = G; cx1 = PW-Gch = cy1-cy0; cw = cx1-cx0n = len(panels)if n == 1:rects = [(cx0,cy0,cx1,cy1)]elif n == 2:hw = (cw-G)//2rects = [(cx0,cy0,cx0+hw,cy1),(cx0+hw+G,cy0,cx1,cy1)]elif n == 3:th = int(ch*0.55); bh2 = ch-th-G; hw = (cw-G)//2by = cy0+th+Grects = [(cx0,cy0,cx1,cy0+th),(cx0,by,cx0+hw,by+bh2),(cx0+hw+G,by,cx1,by+bh2)]else:lw = int(cw*0.55)-G; rw = cw-lw-Gth = int(ch*0.55); bh2 = ch-th-G; sw = (lw-G)//2rx = cx0+lw+G; by = cy0+th+Grects = [(cx0,cy0,cx0+lw,cy0+th),(rx,cy0,rx+rw,cy1),(cx0,by,cx0+sw,cy1),(cx0+sw+G,by,cx0+lw,cy1),]for i,(img_obj,panel_data) in enumerate(panels):if i >= len(rects): breakx1,y1,x2,y2 = rects[i]pw,ph = max(x2-x1,10), max(y2-y1,10)pan = img_obj.resize((pw,ph), Image.LANCZOS)dlgs = panel_data.get('dialogue',[])if dlgs: pan = apply_bubbles(pan, dlgs)pan = add_border(pan, i+1, page_num)page.paste(pan,(x1,y1))return page# ── SCRIPT GENERATION ──────���──────────────────────────────────────────────────def generate_script(topic, num_pages, style, language):lang = 'in Spanish' if language == 'es' else 'in English'prompt = ('You are a professional comic writer. ''Create a ' + str(num_pages) + '-page comic script ' + lang + ' about: ' + str(topic) + '. ''Each page = 4 panels. Characters must be visually consistent (describe clothes, hair, colors). ''Keep each dialogue line under 12 words. ''IMPORTANT: Return ONLY valid JSON, absolutely no markdown or explanation. ''JSON structure: {"title":"...","genre":"...","story_summary":"...",''"characters":[{"name":"...","description":"visual appearance details"}],''"pages":[{"page_number":1,"panels":[{"panel_number":1,"scene":"...","action":"...",''"dialogue":[{"character":"...","text":"short dialogue"}],''"mood":"...","image_prompt":"detailed english visual prompt for AI image generation"}]}]}')# Try multiple free LLM endpointsmodels = ['mistralai/Mistral-7B-Instruct-v0.3','HuggingFaceH4/zephyr-7b-beta','microsoft/Phi-3-mini-4k-instruct',]for model in models:try:client = InferenceClient(model=model, token=HF_TOKEN)response = client.text_generation(prompt,max_new_tokens=6000,temperature=0.7,do_sample=True,)raw = response.strip()m = re.search(r'\{[\s\S]*\}', raw)if m:data = json.loads(m.group())if 'pages' in data and data['pages']:print('Script OK with model: ' + model)return dataexcept Exception as e:print('LLM ' + model + ' err: ' + str(e)[:120])print('All LLMs failed, using fallback script')return fallback_script(topic, num_pages, style, language)def fallback_script(topic, num_pages, style, language):import randomsample_dialogues = [[{'character':'Hero','text':'This ends now! Prepare yourself!'}],[{'character':'Hero','text':'I will protect this land forever!'},{'character':'Villain','text':'You cannot stop what has begun!'}],[{'character':'Hero','text':'Together we are stronger than any darkness!'}],[{'character':'Ally','text':'Watch out! They are surrounding us!'},{'character':'Hero','text':'Stay close. We fight as one.'}],]pages = []for p in range(1, num_pages+1):panels = []for i in range(1,5):seed_idx = (p*4+i) % len(sample_dialogues)panels.append({'panel_number': i,'scene': 'Dramatic scene page '+str(p)+' panel '+str(i),'action': 'Characters in intense action','dialogue': sample_dialogues[seed_idx],'mood': 'intense','image_prompt': (style+' comic book art, '+str(topic)+', page '+str(p)+' panel '+str(i)+', dramatic action scene, professional illustration, vibrant colors, cinematic')})pages.append({'page_number':p,'panels':panels})return {'title':str(topic),'genre':'action','story_summary':'Epic adventure: '+str(topic),'characters':[{'name':'Hero','description':'tall warrior in red and gold armor, determined face, black hair'}],'pages':pages}# ── IMAGE GENERATION ──────────────────────────────────────────────────────────def build_img_prompt(panel, script, style):chars = script.get('characters',[])scene_text = str(panel.get('scene',''))+' '+str(panel.get('action',''))char_descs = [c['description'] for c in charsif c['name'].lower() in scene_text.lower()]base = panel.get('image_prompt') or scene_textreturn (style+' comic book art, professional illustration, highly detailed, dramatic lighting. '+str(base)+'. '+('Characters: '+'; '.join(char_descs[:2])+'. ' if char_descs else '')+'Mood: '+str(panel.get('mood','dramatic'))+'. '+'No text or words in image. Strong linework, vivid colors, cinematic composition.')[:750]def gen_image(prompt, seed):# PRIMARY: Pollinations with FLUX (free, reliable)encoded = urllib.parse.quote(prompt[:500])url = ('https://image.pollinations.ai/prompt/'+encoded+'?width=800&height=600&nologo=true&model=flux&seed='+str(seed)+'&enhance=true')try:r = requests.get(url, timeout=90)if r.status_code==200 and len(r.content)>5000:img = Image.open(BytesIO(r.content)).convert('RGB')return img.resize((800,600), Image.LANCZOS)print('Pollinations status: '+str(r.status_code))except Exception as e:print('Pollinations err: '+str(e)[:80])# FALLBACK: dark placeholder with prompt textimg = Image.new('RGB',(800,600),(25,25,35))dr = ImageDraw.Draw(img)dr.rectangle([4,4,795,595], outline=(120,120,140), width=3)f = font(BOLD,20)dr.text((400,300),'Image loading...', font=f, fill=(160,160,180), anchor='mm')return img# ── MAIN ──────────────────────────────────────────────────────────────────────def generate_comic(topic, num_pages, style, language, hf_token):global HF_TOKENif hf_token and hf_token.strip():HF_TOKEN = hf_token.strip()num_pages = max(1, min(int(num_pages), 32))print('=== Generating: '+str(num_pages)+' pages | '+str(topic)+' ===')script = generate_script(topic, num_pages, style, language)title = script.get('title', str(topic))pages_data = script.get('pages',[])while len(pages_data) < num_pages:fb = fallback_script(topic, 1, style, language)fb['pages'][0]['page_number'] = len(pages_data)+1pages_data.append(fb['pages'][0])jobs = []for pg in pages_data[:num_pages]:for pn, panel in enumerate(pg.get('panels',[])[:4]):prompt = build_img_prompt(panel, script, style)seed = (pg['page_number']*100 + pn + 1) * 31jobs.append((len(jobs), prompt, seed, panel, pg['page_number']))print('Generating '+str(len(jobs))+' panel images in parallel...')results = {}def do_gen(args):idx, prompt, seed, panel, pg_num = argsimg = gen_image(prompt, seed)return idx, img, panel, pg_numwith ThreadPoolExecutor(max_workers=6) as ex:futs = {ex.submit(do_gen,j): j[0] for j in jobs}for f in as_completed(futs):idx, img, panel, pg_num = f.result()results[idx] = (img, panel, pg_num)print('Panel '+str(idx+1)+'/'+str(len(jobs))+' done')page_images = []job_idx = 0for pg in pages_data[:num_pages]:pc = min(len(pg.get('panels',[])),4)panels_for_page = [(results[job_idx+i][0], results[job_idx+i][1])for i in range(pc) if (job_idx+i) in results]job_idx += pcif panels_for_page:page_images.append(compose_page(panels_for_page, pg['page_number'], num_pages, title))return script, page_imagesdef generate_comic_api(topic, num_pages=4, style='manga', language='en', hf_token=''):if not str(topic).strip():return {'error':'Topic required','success':False}script, pages = generate_comic(str(topic), num_pages, style, language, hf_token)out = []for i,pg in enumerate(pages):buf = BytesIO(); pg.save(buf, format='JPEG', quality=90)out.append({'page_number':i+1,'image_base64':base64.b64encode(buf.getvalue()).decode()})return {'success':True,'title':script.get('title',''),'story_summary':script.get('story_summary',''),'characters':script.get('characters',[]),'total_pages':len(pages),'pages':out}def generate_comic_ui(topic, num_pages, style, language, hf_token):if not topic.strip(): return '','',[],'{}'script, pages = generate_comic(topic, num_pages, style, language, hf_token)info = json.dumps({'title':script.get('title',''),'summary':script.get('story_summary',''),'characters':script.get('characters',[]),'total_pages':len(pages)},ensure_ascii=False, indent=2)return script.get('title',topic), script.get('story_summary',''), pages, infoSTYLES=['manga','superhero comic','watercolor comic','noir comic','cartoon','fantasy illustration','sci-fi comic','childrens book illustration']with gr.Blocks(title='Comic AI Generator') as demo:gr.Markdown('# Comic AI Generator')gr.Markdown('Complete comic book: AI art + speech bubbles + professional layout.')with gr.Tabs():with gr.Tab('Generate Comic'):with gr.Row():with gr.Column(scale=1):topic_in = gr.Textbox(label='Story / Topic',placeholder='A ninja cat who saves a village from evil robots', lines=3)pages_in = gr.Slider(1,32,value=2,step=1,label='Pages (4 panels each)')style_in = gr.Dropdown(choices=STYLES,value='manga',label='Art Style')lang_in = gr.Radio(choices=[('English','en'),('Spanish','es')],value='en',label='Language')token_in = gr.Textbox(label='HF Token (optional)',placeholder='hf_...',type='password')gen_btn = gr.Button('Generate Comic',variant='primary',size='lg')gr.Markdown('_2 pages ≈ 2 min • 32 pages ≈ 15 min_')with gr.Column(scale=2):title_out = gr.Textbox(label='Title',interactive=False)summary_out = gr.Textbox(label='Story Summary',interactive=False,lines=3)gallery_out = gr.Gallery(label='Comic Pages',columns=1,rows=4,height='auto')with gr.Accordion('Script JSON',open=False):json_out = gr.Code(language='json')gen_btn.click(fn=generate_comic_ui,inputs=[topic_in,pages_in,style_in,lang_in,token_in],outputs=[title_out,summary_out,gallery_out,json_out])with gr.Tab('API'):gr.Markdown('**POST** `https://bukbuk-comic-ai-generator.hf.space/call/generate_comic_api`\n\n''Params: topic, num_pages (1-32), style, language (en/es), hf_token\n\n''Returns: pages[] with image_base64 JPEG — each page is 1240×1754px (A4), 4-panel layout with speech bubbles')gr.Interface(fn=generate_comic_api,inputs=[gr.Textbox(label='topic'),gr.Number(label='num_pages',value=4),gr.Textbox(label='style',value='manga'),gr.Textbox(label='language',value='en'),gr.Textbox(label='hf_token',value='')],outputs=gr.JSON(label='comic_data'),api_name='generate_comic_api',title='Comic API',description='Returns full comic pages as base64 JPEG images with speech bubbles.')if __name__ == '__main__':demo.launch(share=False)123452 unmodified lines89101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449import gradio as grimport os, json, re, time, base64, requests, urllib.parsefrom PIL import Image, ImageDraw, ImageFontfrom io import BytesIOfrom huggingface_hub import InferenceClient2 unmodified linesHF_TOKEN = os.environ.get('HF_TOKEN', '')# ── FONTS ─────────────────────────────────────────────────────────────────────_BOLD = ['/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf','/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf','/usr/share/fonts/truetype/freefont/FreeSansBold.ttf']_REG = ['/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf','/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf','/usr/share/fonts/truetype/freefont/FreeSans.ttf']def fnt(paths, size):for p in paths:try: return ImageFont.truetype(p, size)except: passtry: return ImageFont.load_default(size=size)except: return ImageFont.load_default()def text_w(draw, txt, f):try: return draw.textlength(str(txt), font=f)except: return len(str(txt)) * (f.size if hasattr(f,'size') else 10)def wrap_text(draw, txt, f, max_w):words = str(txt).split()lines, cur = [], ''for w in words:t = (cur + ' ' + w).strip()if text_w(draw, t, f) <= max_w: cur = telse:if cur: lines.append(cur)cur = wif cur: lines.append(cur)return lines or [str(txt)[:30]]# ── SPEECH BUBBLE (drawn on image) ───────────────────────────────────────────def draw_bubble(img, x1, y1, x2, y2, dialogues):"""Draw speech bubbles inside the panel region [x1,y1,x2,y2]."""if not dialogues: returndraw = ImageDraw.Draw(img)pw, ph = x2-x1, y2-y1f_name = fnt(_BOLD, max(16, ph//18))f_text = fnt(_REG, max(18, ph//16))pad = max(10, ph//30)max_bw = int(pw * 0.82)cursor_y = y1 + max(8, ph//25)for idx, dlg in enumerate(dialogues[:2]):char = str(dlg.get('character',''))text = str(dlg.get('text',''))if not text.strip(): continuelines = wrap_text(draw, text, f_text, max_bw - pad*2 - 10)char_tw = int(text_w(draw, char+':', f_name)) if char else 0line_tw = max((int(text_w(draw, l, f_text)) for l in lines), default=60)bw = min(max(line_tw, char_tw) + pad*2 + 10, max_bw)lh = max(20, int(f_text.size * 1.3) if hasattr(f_text,'size') else 22)bh = lh * len(lines) + pad*2 + (lh if char else 0) + 6# Alternate left / rightif idx % 2 == 0:bx = x1 + max(6, pw//20)else:bx = x2 - bw - max(6, pw//20)by = cursor_yif by + bh > y2 - 8: by = y1 + max(8, ph//25)bx2b, by2b = bx + bw, by + bh# Shadowdraw.rounded_rectangle([bx+3,by+3,bx2b+3,by2b+3], radius=14, fill=(0,0,0))# Bubbledraw.rounded_rectangle([bx,by,bx2b,by2b], radius=14,fill=(255,255,255), outline=(10,10,10), width=3)# Tailtx = bx + bw//2draw.polygon([(tx-10,by2b),(tx+10,by2b),(tx,by2b+16)], fill=(255,255,255))draw.line([(tx-10,by2b),(tx,by2b+16)], fill=(10,10,10), width=3)draw.line([(tx+10,by2b),(tx,by2b+16)], fill=(10,10,10), width=3)ty = by + pad//2if char:draw.text((bx+pad, ty), char+':', font=f_name, fill=(15,15,200))ty += lhfor line in lines:draw.text((bx+pad, ty), line, font=f_text, fill=(5,5,5))ty += lhcursor_y = by2b + max(8, ph//30)# ── PAGE LAYOUT: 4 panel rects inside content area ────────────────────────────def panel_rects(x0, y0, x1, y1, n):"""Return list of (px1,py1,px2,py2) for n panels, dynamic layout."""g = 8w, h = x1-x0, y1-y0if n == 1:return [(x0,y0,x1,y1)]if n == 2:hw = (w - g) // 2return [(x0,y0,x0+hw,y1),(x0+hw+g,y0,x1,y1)]if n == 3:th = int(h*0.55)hw = (w - g) // 2return [(x0,y0,x1,y0+th),(x0,y0+th+g,x0+hw,y1),(x0+hw+g,y0+th+g,x1,y1)]# 4 panels — asymmetric cinematic layoutlw = int(w*0.54)rw = w - lw - gth = int(h*0.52)bh = h - th - gsw = (lw - g) // 2return [(x0, y0, x0+lw, y0+th), # top-left big(x0+lw+g, y0, x1, y1), # right tall(x0, y0+th+g, x0+sw, y1), # bottom-left small(x0+sw+g, y0+th+g, x0+lw, y1), # bottom-right small]# ── COMPOSE FULL PAGE ─────────────────────────────────────────────────────────def compose_full_page(page_img_1240, panels_data, page_num, total, title):"""page_img_1240: PIL Image 1240x1340 (the AI-generated full-page art)panels_data: list of panel dicts with dialogueReturns final 1240x1754 page."""PW, PH = 1240, 1754HH, FH, G = 58, 40, 10page = Image.new('RGB', (PW, PH), (255,255,255))# ── Headerdraw = ImageDraw.Draw(page)draw.rectangle([0,0,PW,HH], fill=(10,10,10))draw.text((PW//2, HH//2), title.upper()[:64],font=fnt(_BOLD,26), fill=(255,255,255), anchor='mm')# ── Footerfy = PH - FHdraw.rectangle([0,fy,PW,PH], fill=(215,215,215))draw.text((PW//2, fy+FH//2), str(page_num)+' / '+str(total),font=fnt(_REG,20), fill=(55,55,55), anchor='mm')# ── Content areacx0, cy0, cx1, cy1 = G, HH+G, PW-G, fy-Gcw, ch = cx1-cx0, cy1-cy0# Scale AI art to content areaart_scaled = page_img_1240.resize((cw, ch), Image.LANCZOS)page.paste(art_scaled, (cx0, cy0))# ── Draw panel borders + speech bubblesrects = panel_rects(cx0, cy0, cx1, cy1, min(len(panels_data), 4))draw = ImageDraw.Draw(page) # refresh after pastefor i, (rx1,ry1,rx2,ry2) in enumerate(rects):# Panel borderdraw.rectangle([rx1,ry1,rx2,ry2], outline=(0,0,0), width=5)# Badgebadge = str(page_num)+'-'+str(i+1)fb = fnt(_BOLD, 16)bw2 = int(text_w(draw, badge, fb)) + 10draw.rectangle([rx2-bw2-3, ry2-24, rx2-3, ry2-3], fill=(0,0,0))draw.text((rx2-bw2//2-3, ry2-13), badge, font=fb, fill=(255,255,255), anchor='mm')# Bubblesif i < len(panels_data):draw_bubble(page, rx1, ry1, rx2, ry2, panels_data[i].get('dialogue',[]))return page# ── IMAGE GENERATION: 1 call per page ─────────────────────────────────────────def build_page_prompt(page_data, script, style):"""Build a single prompt describing the whole page layout for AI generation."""chars = script.get('characters', [])char_ref = '. '.join(c['description'] for c in chars[:2])panels = page_data.get('panels', [])[:4]n = len(panels)layout_desc = {1: 'single full-page splash panel',2: 'two side-by-side horizontal panels',3: 'large panel on top, two smaller panels on the bottom row',4: 'asymmetric layout: large panel top-left, tall panel on the right, two small panels bottom-left',}.get(n, 'four panels')scenes = []for i, p in enumerate(panels):s = 'Panel ' + str(i+1) + ': ' + str(p.get('image_prompt') or p.get('scene',''))scenes.append(s)prompt = (style + ' comic book page, professional comic book art, high detail, dramatic lighting. ''Comic page layout with ' + layout_desc + '. '+ ' | '.join(scenes) + '. ''Consistent character design throughout: ' + char_ref + '. ''Vibrant colors, strong linework, cinematic composition. ''NO text or words in the image.')return prompt[:900]def fetch_page_image(prompt, seed, retries=3):"""Fetch one full-page image from Pollinations with retries."""encoded = urllib.parse.quote(prompt[:600])url = ('https://image.pollinations.ai/prompt/' + encoded +'?width=1220&height=1636&nologo=true&model=flux''&seed=' + str(seed) + '&enhance=true')for attempt in range(retries):try:if attempt > 0:wait = 4 * attemptprint(' retry ' + str(attempt) + ' in ' + str(wait) + 's...')time.sleep(wait)r = requests.get(url, timeout=120)if r.status_code == 200 and len(r.content) > 8000:img = Image.open(BytesIO(r.content)).convert('RGB')return img.resize((1220, 1636), Image.LANCZOS)print(' Pollinations p' + str(seed) + ' status=' + str(r.status_code))except Exception as e:print(' Pollinations err: ' + str(e)[:80])return None # caller will use placeholderdef make_page_placeholder(page_num, panels_data, style):img = Image.new('RGB', (1220, 1636), (28, 28, 38))draw = ImageDraw.Draw(img)draw.rectangle([4,4,1215,1631], outline=(100,100,120), width=4)f = fnt(_BOLD, 28)draw.text((610, 818), style.upper() + ' PAGE ' + str(page_num),font=f, fill=(140,140,160), anchor='mm')fr = fnt(_REG, 20)draw.text((610, 870), '(image generation failed — retrying on next run)',font=fr, fill=(100,100,110), anchor='mm')return img# ── SCRIPT GENERATION ──────���──────────────────────────────────────────────────def generate_script(topic, num_pages, style, language):lang = 'in Spanish' if language == 'es' else 'in English'system = ('You are a professional comic book writer and artist. ''Create a complete ' + str(num_pages) + '-page comic script ' + lang + ' about: ' + str(topic) + '. ''Each page has exactly 4 panels. ''Define 1-3 main characters with detailed visual descriptions (hair, clothes, colors). ''Keep each dialogue text under 12 words. ''Each image_prompt must be in English, vivid and specific for AI art generation. ''Return ONLY valid JSON — no markdown fences, no explanation:\n''{"title":"string","genre":"string","story_summary":"string",''"characters":[{"name":"string","description":"full visual description"}],''"pages":[{"page_number":1,"panels":[{"panel_number":1,''"scene":"string","action":"string",''"dialogue":[{"character":"name","text":"short text"}],''"mood":"string","image_prompt":"detailed english art prompt"}]}]}')models = ['mistralai/Mistral-7B-Instruct-v0.3','HuggingFaceH4/zephyr-7b-beta','microsoft/Phi-3-mini-4k-instruct','tiiuae/falcon-7b-instruct',]for model in models:for attempt in range(2):try:client = InferenceClient(model=model, token=HF_TOKEN)raw = client.text_generation('[INST] ' + system + ' [/INST]',max_new_tokens=7000, temperature=0.7, do_sample=True)m = re.search(r'\{[\s\S]*\}', raw.strip())if m:data = json.loads(m.group())if 'pages' in data and len(data['pages']) >= 1:print('Script OK with ' + model)return dataexcept Exception as e:err = str(e)[:80]print('LLM ' + model + ' attempt ' + str(attempt) + ': ' + err)if '402' in err or '429' in err:break # skip this model entirelytime.sleep(2)print('Using built-in fallback script')return fallback_script(topic, num_pages, style, language)def fallback_script(topic, num_pages, style, language):DIALOGUES = [[{'character':'Hero','text':'This ends now! No more running!'}],[{'character':'Hero','text':'I will protect them all, no matter what.'},{'character':'Villain','text':'Your courage is admirable — and useless.'}],[{'character':'Ally','text':'Watch out! They surround us from both sides!'},{'character':'Hero','text':'Stay close. We fight together.'}],[{'character':'Hero','text':'Is this the power they warned us about?'}],[{'character':'Villain','text':'Did you really think you could defeat me?'}],[{'character':'Hero','text':'It is not over. Not while I still stand!'}],]pages = []for p in range(1, num_pages+1):panels = []for i in range(1,5):dlg = DIALOGUES[(p*4+i) % len(DIALOGUES)]panels.append({'panel_number': i,'scene': 'Dramatic scene ' + str(p) + '-' + str(i),'action': 'Intense action','dialogue': dlg,'mood': 'intense','image_prompt': (style + ' comic art, ' + str(topic) +', dramatic scene, panel ' + str(i) +' of page ' + str(p) +', cinematic lighting, professional illustration')})pages.append({'page_number': p, 'panels': panels})return {'title': str(topic), 'genre': 'action','story_summary': 'Epic adventure: ' + str(topic),'characters': [{'name':'Hero','description':'tall warrior in red and gold armor, black hair, determined expression'},{'name':'Villain','description':'dark-robed figure with silver mask and glowing purple eyes'}],'pages': pages}# ── MAIN GENERATION ───────────────────────────────────────────────────────────def generate_comic(topic, num_pages, style, language, hf_token):global HF_TOKENif hf_token and hf_token.strip():HF_TOKEN = hf_token.strip()num_pages = max(1, min(int(num_pages), 32))print('=== Comic: ' + str(num_pages) + 'p | ' + str(topic) + ' ===')script = generate_script(topic, num_pages, style, language)title = script.get('title', str(topic))pages_data = script.get('pages', [])# Pad missing pageswhile len(pages_data) < num_pages:fb = fallback_script(topic, 1, style, language)fb['pages'][0]['page_number'] = len(pages_data) + 1pages_data.append(fb['pages'][0])print('Generating ' + str(num_pages) + ' full-page images (1 API call each)...')def gen_one_page(pg):pnum = pg['page_number']prompt = build_page_prompt(pg, script, style)seed = pnum * 137 + 42print(' Page ' + str(pnum) + '/' + str(num_pages) + ' requesting...')art = fetch_page_image(prompt, seed)if art is None:art = make_page_placeholder(pnum, pg.get('panels',[]), style)final = compose_full_page(art, pg.get('panels',[])[:4], pnum, num_pages, title)print(' Page ' + str(pnum) + ' composed OK')return pnum, final# Sequential with small delay to avoid Pollinations rate limitpage_results = {}for pg in pages_data[:num_pages]:pnum, final = gen_one_page(pg)page_results[pnum] = finaltime.sleep(1.5) # respectful rate limitingordered = [page_results[i+1] for i in range(num_pages) if (i+1) in page_results]return script, ordereddef generate_comic_api(topic, num_pages=4, style='manga', language='en', hf_token=''):if not str(topic).strip():return {'error': 'Topic required', 'success': False}script, pages = generate_comic(str(topic), num_pages, style, language, hf_token)out = []for i, pg in enumerate(pages):buf = BytesIO()pg.save(buf, format='JPEG', quality=92)out.append({'page_number': i+1,'image_base64': base64.b64encode(buf.getvalue()).decode(),'format': 'JPEG', 'size': '1240x1754'})return {'success': True,'title': script.get('title',''),'story_summary': script.get('story_summary',''),'genre': script.get('genre',''),'characters': script.get('characters',[]),'total_pages': len(pages),'pages': out}def generate_comic_ui(topic, num_pages, style, language, hf_token):if not topic.strip():return '', '', [], '{}'script, pages = generate_comic(topic, num_pages, style, language, hf_token)info = json.dumps({'title': script.get('title',''),'summary': script.get('story_summary',''),'characters': script.get('characters',[]),'total_pages': len(pages),'api_note': '1 full-page JPEG per page, 1240x1754px, speech bubbles included'}, ensure_ascii=False, indent=2)return script.get('title', topic), script.get('story_summary',''), pages, info# ── UI ────────────────────────────────────────────────────────────────────────STYLES = ['manga','superhero comic','watercolor comic','noir comic','cartoon','fantasy illustration','sci-fi comic','childrens book illustration']with gr.Blocks(title='Comic AI Generator') as demo:gr.Markdown('# Comic AI Generator')gr.Markdown('Generates a full comic book — **1 AI image per page**, ''each page 1240×1754 px with panel borders and speech bubbles.')with gr.Tabs():with gr.Tab('Generate Comic'):with gr.Row():with gr.Column(scale=1):topic_in = gr.Textbox(label='Story / Topic',placeholder='A pirate captain who discovers a mythical treasure island...', lines=3)pages_in = gr.Slider(1, 32, value=2, step=1, label='Number of Pages')style_in = gr.Dropdown(choices=STYLES, value='manga', label='Art Style')lang_in = gr.Radio(choices=[('English','en'),('Spanish','es')], value='en', label='Language')token_in = gr.Textbox(label='HF Token (optional)', placeholder='hf_...', type='password')gen_btn = gr.Button('Generate Comic', variant='primary', size='lg')gr.Markdown('_1 page ≈ 30s · 4 pages ≈ 2 min · 32 pages ≈ 16 min_')with gr.Column(scale=2):title_out = gr.Textbox(label='Title', interactive=False)summary_out = gr.Textbox(label='Story Summary', interactive=False, lines=3)gallery_out = gr.Gallery(label='Comic Pages', columns=1, rows=4, height='auto')with gr.Accordion('Script / API info (JSON)', open=False):json_out = gr.Code(language='json')gen_btn.click(fn=generate_comic_ui,inputs=[topic_in, pages_in, style_in, lang_in, token_in],outputs=[title_out, summary_out, gallery_out, json_out])with gr.Tab('API'):gr.Markdown('## REST API\n\n''**POST** `https://bukbuk-comic-ai-generator.hf.space/call/generate_comic_api`\n\n''### Request body\n''```json\n{"data":["topic", num_pages, "style", "language", "hf_token"]}\n```\n\n''### Response\n''Returns `pages[]` array — each item: `page_number` + `image_base64` (JPEG 1240×1754).\n\n''Each page is **one complete comic page image** with AI art, panel borders and speech bubbles.\n\n''**32 pages = 32 API calls to Pollinations** (1 per page), not 128.')gr.Interface(fn=generate_comic_api,inputs=[gr.Textbox(label='topic'), gr.Number(label='num_pages', value=4),gr.Textbox(label='style', value='manga'),gr.Textbox(label='language', value='en'),gr.Textbox(label='hf_token', value='')],outputs=gr.JSON(label='comic_data'),api_name='generate_comic_api',title='Comic API',description='1 full comic page per image. Each JPEG 1240x1754px includes AI art + panel borders + speech bubbles.')if __name__ == '__main__':demo.launch(share=False)
app.py+362-278