import urllib.parse
import gradio as gr
# -------------------------------------------------
# Badge URL generation
# └▶ HEX 컬러 앞의 ‘#’ 기호를 제거하여 Shields.io 가
# 색상을 올바르게 인식하도록 수정했습니다.
# -------------------------------------------------
def generate_static_badge(
label, message,
color, label_color,
logo, logo_color,
style, link
):
# 1) ColorPicker 값에서 ‘#’ 제거
strip_hash = lambda c: c.lstrip("#") if isinstance(c, str) else c
color = strip_hash(color)
label_color = strip_hash(label_color)
logo_color = strip_hash(logo_color)
# 2) Shields.io 쿼리 파라미터 구성
base = "https://img.shields.io/static/v1"
params = []
if label:
params.append(f"label={urllib.parse.quote(label, safe='')}")
if message:
params.append(f"message={urllib.parse.quote(message, safe='')}")
if color:
params.append(f"color={urllib.parse.quote(color, safe='')}")
if label_color:
params.append(f"labelColor={urllib.parse.quote(label_color, safe='')}")
if logo:
params.append(f"logo={urllib.parse.quote(logo, safe='')}")
if logo_color:
params.append(f"logoColor={urllib.parse.quote(logo_color, safe='')}")
if style:
params.append(f"style={urllib.parse.quote(style, safe='')}")
badge_url = base + ("?" + "&".join(params) if params else "")
html_img = f'
'
# 3) 링크 감쌀지 여부
html_code = (
f'{html_img}'
if link else html_img
)
# 4) 미리보기 카드
badge_preview = f"""
{html_code}
"""
return html_code, badge_preview
# -------------------------------------------------
# Gradio UI
# -------------------------------------------------
with gr.Blocks(theme=gr.themes.Soft()) as demo:
# ---------- Global CSS ----------
gr.HTML("""
""")
# ---------- Header ----------
gr.HTML("""
🎨 BadgeCraft
Create beautiful badges with live preview and HTML snippet
✨ MIT License
👥 Created by OpenFreeAI Team
""")
# ---------- Tabs ----------
with gr.Tabs():
# ▷▷ Badge Generator 탭
with gr.TabItem("Badge Generator"):
with gr.Row():
# ----- 설정 입력 -----
with gr.Column():
with gr.Group(elem_classes="badge-section"):
gr.HTML("✏️ Badge Settings
")
label = gr.Textbox(label="Label", value="Discord", lines=1, elem_id="label-input")
message = gr.Textbox(label="Message", value="Join our community", lines=1, elem_id="message-input")
logo = gr.Textbox(label="Logo", value="discord", lines=1, elem_id="logo-input")
style = gr.Dropdown(
label="Style",
choices=["flat","flat-square","plastic","for-the-badge","social"],
value="for-the-badge",
elem_id="style-input")
color = gr.ColorPicker(label="Background Color", value="#5865F2", elem_id="color-input")
label_color = gr.ColorPicker(label="Label Background Color", value="#99AAFF", elem_id="label-color-input")
logo_color = gr.ColorPicker(label="Logo Color", value="#ffffff", elem_id="logo-color-input")
link = gr.Textbox(label="Link (URL)", value="https://discord.gg/openfreeai", lines=1, elem_id="link-input")
# ----- 미리보기 & 코드 -----
with gr.Column():
with gr.Group(elem_classes="badge-section"):
gr.HTML("👁️ Preview
")
out_preview = gr.HTML(label="")
with gr.Group(elem_classes="badge-section"):
gr.HTML("💻 HTML Code
")
out_code = gr.Code(label="", language="html", lines=3)
# 예제 데이터
examples = [
["Discord", "Openfree AI", "#5865F2", "#99AAFF", "discord", "white", "for-the-badge", "https://discord.gg/openfreeai"],
["X.com", "Follow us", "#1DA1F2", "#00CFFF", "x", "white", "for-the-badge", "https://x.com/openfree_ai"],
["Collections","Explore", "#FFB300", "#FFF176", "huggingface","black", "for-the-badge", "https://huggingface.co/collections/VIDraft/best-open-ai-services-68057e6e312880ea92abaf4c"],
["GitHub", "Star us", "#0A0A0A", "#39FF14", "github", "white", "for-the-badge", "https://github.com/openfreeai"],
["YouTube", "Watch now", "#E50000", "#FF5E5E", "youtube", "white", "for-the-badge", "https://www.youtube.com/@AITechTree"],
["Facebook", "Like us", "#1877F2", "#6FAFFF", "facebook", "white", "for-the-badge", "https://www.facebook.com/profile.php?id=61575353674679"],
["Instagram", "友情 萬世", "#E4405F", "#FF77A9", "instagram", "white", "for-the-badge", "https://www.instagram.com/openfree_ai/"],
["Threads", "함께 즐겨요.", "#000000", "#FF00FF", "threads", "white", "for-the-badge", "https://www.threads.net/@openfree_ai"],
]
# 예제 그리드 HTML
html_items = ''
for idx, ex in enumerate(examples):
badge_url = (
"https://img.shields.io/static/v1?" + "&".join([
f"label={urllib.parse.quote(ex[0],safe='')}",
f"message={urllib.parse.quote(ex[1],safe='')}",
f"color={urllib.parse.quote(ex[2].lstrip('#'),safe='')}",
f"labelColor={urllib.parse.quote(ex[3].lstrip('#'),safe='')}",
f"logo={urllib.parse.quote(ex[4],safe='')}",
f"logoColor={urllib.parse.quote(ex[5],safe='')}",
f"style={urllib.parse.quote(ex[6],safe='')}"
])
)
html_items += f'''
{ex[0]}
'''
html_items += '
'
# ------------- React Controlled Input Hack -------------
hack_js = """
function updateReactValue(el,newVal){
if(!el)return;
let prototype=window.HTMLInputElement.prototype;
if(el.tagName==="TEXTAREA")prototype=window.HTMLTextAreaElement.prototype;
const descriptor=Object.getOwnPropertyDescriptor(prototype,"value");
descriptor.set.call(el,newVal);
el.dispatchEvent(new Event("input",{bubbles:true}));
el.dispatchEvent(new Event("change",{bubbles:true}));
}
function convertToHexIfNeeded(c){
if(!c)return"#000000";
if(c.toLowerCase()==="white")return"#ffffff";
if(c.toLowerCase()==="black")return"#000000";
return c;
}
function setColorValue(elemId,val){
const container=document.getElementById(elemId);
if(!container)return;
let input=container.querySelector("input[type='color']");
if(!input)input=container.querySelector("input[type='text']");
if(!input)return;
updateReactValue(input,val);
}
"""
# 예제 클릭 시 자동 채우기
apply_example_js = f"""
"""
gr.HTML(html_items + apply_example_js)
# ---------- 초기 로드 & 실시간 업데이트 ----------
demo.load(
fn=generate_static_badge,
inputs=[label,message,color,label_color,logo,logo_color,style,link],
outputs=[out_code,out_preview]
)
for inp in [label,message,color,label_color,logo,logo_color,style,link]:
inp.change(
fn=generate_static_badge,
inputs=[label,message,color,label_color,logo,logo_color,style,link],
outputs=[out_code,out_preview]
)
# ▷▷ Help 탭
with gr.TabItem("Help"):
gr.HTML('''
📋 How to Use BadgeCraft
✨ What are Badges?
Badges are small visual indicators that can be used in README files, websites, and documentation. Shields.io badges are widely used to display project status, social media links, version information, and more.
🛠️ Basic Settings
- Label: Text displayed on the left side of the badge (e.g., "Discord", "Version", "Status")
- Message: Text displayed on the right side of the badge
- Logo: Name of a logo provided by Simple Icons (View List)
- Style: Determines the shape of the badge (flat, plastic, for-the-badge, etc.)
🎨 Color Settings
- Background Color: Background color for the right side of the badge
- Label Background Color: Background color for the left side of the badge
- Logo Color: Color of the logo (e.g. white or black)
🔗 Using the HTML
Copy the generated HTML code and paste it into your website, blog, GitHub README, etc.
HTML works in GitHub READMEs, but if you prefer markdown, use 
.
💡 Tips
- Click on any example in the grid to automatically fill in all settings
- The preview updates in real-time as you make changes
- You can use over 2000+ logos from Simple Icons — just enter the name
- Custom colors can be selected with the color picker or by entering a hex code
''')
# ---------- Footer ----------
gr.HTML('''
''')
# -------------------------------------------------
# Launch
# -------------------------------------------------
if __name__ == "__main__":
demo.launch()