Update app.py
Browse filesTiga perubahan saja:
1. theme dan css dipindah dari gr.Blocks() ke demo.launch()
2. show_copy_button=True dihapus dari Textbox
3. gr.CopyButton(value=box) ditambahkan di samping setiap Textbox
23 unmodified lines24252627282930313233343536373839404148 unmodified lines9091929394959697989910010110210310410510610711 unmodified lines11912012112212312412513 unmodified lines13914014114214314414510 unmodified lines15615715815916016116215 unmodified lines1781791801811821831841851861871881891901918 unmodified lines2002012022032042052062072082092102112122132142152166 unmodified lines22322422522622722822913 unmodified lines2432442452462472482497 unmodified lines2572582592602612622632642652665 unmodified lines27227327427527627727827928028128228328428528628728820 unmodified lines3093103113123133143153163173183193203213223233243253266 unmodified lines33333433533633733833934034134249 unmodified lines3923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324331 unmodified line43543643743843923 unmodified lines# KONFIGURASI MODEL# ══════════════════════════════════════════════════════# Pilih salah satu (hapus tanda # di depan yang mau dipakai):MODEL_NAME = "Qwen/Qwen2.5-3B-Instruct" # ← RECOMMENDED, bagus buat Indo# MODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct" # ← Lebih ringan, cukup bagus# MODEL_NAME = "meta-llama/Llama-3.2-1B-Instruct" # ← Paling ringan, kualitas lower# MODEL_NAME = "google/gemma-2-2b-it" # ← Alternatif bagusHF_TOKEN = os.environ.get("HF_TOKEN", "")CHAT_API = f"https://api-inference.huggingface.co/models/{MODEL_NAME}/v1/chat/completions"TEXT_API = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"# ══════════════════════════════════════════════════════# DATA PLATFORM, GAYA, BAHASA# ══════════════════════════════════════════════════════PLATFORMS = {48 unmodified lines# ══════════════════════════════════════════════════════# LOGIC — API CALL & GENERATE# ══════════════════════════════════════════════════════def call_api(messages):"""Panggil HF Inference API (chat dulu, fallback ke text)"""headers = {"Authorization": f"Bearer {HF_TOKEN}","Content-Type": "application/json"}params = {"max_tokens": 1000, "temperature": 0.85, "top_p": 0.9}# ── Attempt 1: Chat Completions API ──try:resp = requests.post(CHAT_API, headers=headers,11 unmodified linesexcept Exception:pass# ── Attempt 2: Text Generation API (fallback) ──try:prompt = f"{messages[0]['content']}\n\n{messages[1]['content']}"resp = requests.post(13 unmodified linesdata = resp.json()if isinstance(data, list) and "generated_text" in data[0]:text = data[0]["generated_text"]# Strip prompt kalau ikut ke-returnif prompt in text:text = text.replace(prompt, "").strip()return text10 unmodified linesdef clean_text(text):"""Hapus preamble yang sering muncul dari model"""if not text:return textunwanted = [15 unmodified linesdef parse_captions(raw_text, jumlah):"""Parse response jadi list caption individual"""text = clean_text(raw_text)parts = [p.strip() for p in text.split("---") if p.strip()]captions = []for p in parts:p = p.strip()# Hapus nomor di awal kalau adaif len(p) > 2 and p[0].isdigit() and p[1] in ".)":p = p[2:].strip()if len(p) > 15:8 unmodified linesdef generate_caption(konteks, platform, gaya, bahasa, jumlah):"""Fungsi utama generate — return values + visibility"""error_all_visible = tuple([gr.update(visible=True)] * 5)# Validasi kosongif not konteks or not konteks.strip():vals = ["⚠️ Tulis dulu deskripsi foto/konten kamu di kolom atas!"] + [""] * 4return tuple(gr.update(value=v, visible=True) for v in vals)# Validasi tokenif not HF_TOKEN:msg = ("⚠️ TOKEN BELUM DISET!\n\n"6 unmodified linesvals = [msg] + [""] * 4return tuple(gr.update(value=v, visible=True) for v in vals)# Bangun user promptuser_msg = f"""PLATFORM: {platform}{PLATFORMS[platform]}13 unmodified lines{"role": "user", "content": user_msg}]# Panggil APIresult = call_api(messages)error_map = {7 unmodified linesvals = [error_map[result]] + [""] * 4return tuple(gr.update(value=v, visible=True) for v in vals)# Parse captioncaptions = parse_captions(result, jumlah)# Bangun output dengan value + visibilityoutput = []for i in range(5):if i < jumlah:5 unmodified linesdef update_visibility(jumlah):"""Update visibility saat dropdown jumlah berubah"""return tuple(gr.update(visible=(i < jumlah)) for i in range(5))def fill_preset(name):"""Isi konteks dari tombol preset"""return PRESETS.get(name, "")# ══════════════════════════════════════════════════════# UI — GRADIO INTERFACE# ══════════════════════════════════════════════════════CUSTOM_CSS = """20 unmodified lines}"""with gr.Blocks(title="CapGen AI — Caption Generator Indonesia",theme=gr.themes.Soft(primary_hue="orange",secondary_hue="amber",neutral_hue="stone",font=gr.themes.GoogleFont("Inter"),),css=CUSTOM_CSS,) as demo:# ── HEADER ──gr.Markdown("""<div style="text-align:center; padding:8px 0 4px 0;"><h1 style="margin:0;">✍️ CapGen AI</h1>6 unmodified lines</div>""")# ── MAIN: 2 KOLOM ──with gr.Row(equal_height=False):# ── KOLOM KIRI: INPUT ──with gr.Column(scale=1):gr.Markdown("### 📝 Ceritakan Foto/Konten Kamu")49 unmodified lineselem_id="btn-generate",)# ── KOLOM KANAN: OUTPUT ──with gr.Column(scale=1):gr.Markdown("### 📋 Hasil Caption")gr.Markdown('<span style="font-size:12px;color:#999;">''Klik ikon 📋 di pojok kanan untuk copy</span>')caption_boxes = []for i in range(5):box = gr.Textbox(label=f"Caption {i + 1}",lines=4,max_lines=8,show_copy_button=True,interactive=False,visible=(i < 3),elem_classes=["caption-output"],)caption_boxes.append(box)# Visibility update saat jumlah berubahjumlah.change(fn=update_visibility,inputs=[jumlah],outputs=caption_boxes,)# Generate captionbtn_generate.click(fn=generate_caption,inputs=[konteks, platform, gaya, bahasa, jumlah],outputs=caption_boxes,)# ── FOOTER ──gr.Markdown('<div class="footer-text">'"Dibuat dengan ❤️ untuk komunitas Indonesia · "1 unmodified line"</div>")# ── JALANKAN ──demo.launch()23 unmodified lines242526272829303132333435363738394048 unmodified lines899091929394959697989910010110210310411 unmodified lines11611711811912012113 unmodified lines13513613713813914010 unmodified lines15115215315415515615 unmodified lines1721731741751761771781791801811821838 unmodified lines1921931941951961971981992002016 unmodified lines20820921021121221313 unmodified lines2272282292302312327 unmodified lines2402412422432442452462475 unmodified lines25325425525625725825926026126226326426526626720 unmodified lines2882892902912922932942956 unmodified lines30230330430530630730830949 unmodified lines3593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044051 unmodified line40740840941041141241341441541641723 unmodified lines# KONFIGURASI MODEL# ══════════════════════════════════════════════════════MODEL_NAME = "Qwen/Qwen2.5-3B-Instruct"# MODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct"# MODEL_NAME = "meta-llama/Llama-3.2-1B-Instruct"# MODEL_NAME = "google/gemma-2-2b-it"HF_TOKEN = os.environ.get("HF_TOKEN", "")CHAT_API = f"https://api-inference.huggingface.co/models/{MODEL_NAME}/v1/chat/completions"TEXT_API = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"# ══════════════════════════════════════════════════════# DATA# ══════════════════════════════════════════════════════PLATFORMS = {48 unmodified lines# ══════════════════════════════════════════════════════# LOGIC# ══════════════════════════════════════════════════════def call_api(messages):headers = {"Authorization": f"Bearer {HF_TOKEN}","Content-Type": "application/json"}params = {"max_tokens": 1000, "temperature": 0.85, "top_p": 0.9}try:resp = requests.post(CHAT_API, headers=headers,11 unmodified linesexcept Exception:passtry:prompt = f"{messages[0]['content']}\n\n{messages[1]['content']}"resp = requests.post(13 unmodified linesdata = resp.json()if isinstance(data, list) and "generated_text" in data[0]:text = data[0]["generated_text"]if prompt in text:text = text.replace(prompt, "").strip()return text10 unmodified linesdef clean_text(text):if not text:return textunwanted = [15 unmodified linesdef parse_captions(raw_text, jumlah):text = clean_text(raw_text)parts = [p.strip() for p in text.split("---") if p.strip()]captions = []for p in parts:p = p.strip()if len(p) > 2 and p[0].isdigit() and p[1] in ".)":p = p[2:].strip()if len(p) > 15:8 unmodified linesdef generate_caption(konteks, platform, gaya, bahasa, jumlah):if not konteks or not konteks.strip():vals = ["⚠️ Tulis dulu deskripsi foto/konten kamu di kolom atas!"] + [""] * 4return tuple(gr.update(value=v, visible=True) for v in vals)if not HF_TOKEN:msg = ("⚠️ TOKEN BELUM DISET!\n\n"6 unmodified linesvals = [msg] + [""] * 4return tuple(gr.update(value=v, visible=True) for v in vals)user_msg = f"""PLATFORM: {platform}{PLATFORMS[platform]}13 unmodified lines{"role": "user", "content": user_msg}]result = call_api(messages)error_map = {7 unmodified linesvals = [error_map[result]] + [""] * 4return tuple(gr.update(value=v, visible=True) for v in vals)captions = parse_captions(result, jumlah)output = []for i in range(5):if i < jumlah:5 unmodified linesdef update_visibility(jumlah):return tuple(gr.update(visible=(i < jumlah)) for i in range(5))def fill_preset(name):return PRESETS.get(name, "")# ══════════════════════════════════════════════════════# UI# ══════════════════════════════════════════════════════CUSTOM_CSS = """20 unmodified lines}"""with gr.Blocks() as demo:gr.Markdown("""<div style="text-align:center; padding:8px 0 4px 0;"><h1 style="margin:0;">✍️ CapGen AI</h1>6 unmodified lines</div>""")with gr.Row(equal_height=False):with gr.Column(scale=1):gr.Markdown("### 📝 Ceritakan Foto/Konten Kamu")49 unmodified lineselem_id="btn-generate",)with gr.Column(scale=1):gr.Markdown("### 📋 Hasil Caption")gr.Markdown('<span style="font-size:12px;color:#999;">''Klik tombol 📋 untuk copy tiap caption</span>')caption_boxes = []caption_groups = []for i in range(5):with gr.Group(visible=(i < 3)) as group:with gr.Row():box = gr.Textbox(label=f"Caption {i + 1}",lines=4,max_lines=8,interactive=False,elem_classes=["caption-output"],scale=5,)copy_btn = gr.CopyButton(value=box, scale=1)caption_boxes.append(box)caption_groups.append(group)jumlah.change(fn=update_visibility,inputs=[jumlah],outputs=caption_groups,)btn_generate.click(fn=generate_caption,inputs=[konteks, platform, gaya, bahasa, jumlah],outputs=caption_boxes,)btn_generate.click(fn=update_visibility,inputs=[jumlah],outputs=caption_groups,)gr.Markdown('<div class="footer-text">'"Dibuat dengan ❤️ untuk komunitas Indonesia · "1 unmodified line"</div>")demo.launch(theme=gr.themes.Soft(primary_hue="orange",secondary_hue="amber",neutral_hue="stone",),css=CUSTOM_CSS,)
app.py+37-59