Update app.py
Browse files12345678910111213141516171819201 unmodified line22232425262728293031323334353637383940414243444546474849505152535455565758596061626364655 unmodified lines71727374757677787980import osimport gradio as grfrom huggingface_hub.inference_api import InferenceApifrom PIL import Imageimport io# 1. InferenceApi initialisieren (ohne zwingendes Token)## Wenn HF_TOKEN gesetzt ist, übergeben wir ihn,# ansonsten initialisieren wir ohne Token (funktioniert bei öffentlichen Spaces).HF_TOKEN = os.getenv("HF_TOKEN")REMOTE_SPACE = "black-forest-labs/FLUX.1-schnell"if HF_TOKEN:inference = InferenceApi(repo_id=REMOTE_SPACE, token=HF_TOKEN)else:inference = InferenceApi(repo_id=REMOTE_SPACE)def proxy_generate(prompt: str,num_inference_steps: int = 4,1 unmodified lineheight: int = 512,width: int = 512):"""Proxy-Funktion für Flux-Schnell:• prompt: Texteingabe für die Bildsynthese• num_inference_steps: Anzahl der Diffusionsschritte• guidance_scale: CFG-Skalierungsfaktor• height, width: Höhe/Breite des Ausgabebildes"""# 2. Payload für das entfernte Space-API formenpayload = {"inputs": {"prompt": prompt,"height": height,"width": width,"num_inference_steps": num_inference_steps,"guidance_scale": guidance_scale}}# 3. API-Aufruf: POST ans Space-Repositoryresponse = inference(payload)# 4. Aus dem Response-Dict das Bild extrahierenimage_data = response.get("data")if isinstance(image_data, list) and image_data:# Manche Spaces liefern Liste mit Base64-Stringbase64_str = image_data[0]image = Image.open(io.BytesIO(bytearray(base64_str, "utf-8")))elif isinstance(image_data, (bytes, bytearray)):# Direkte Bytes-Antwortimage = Image.open(io.BytesIO(image_data))else:raise ValueError(f"Unerwartetes Response-Format: {type(image_data)}")return image# 5. Gradio-Interface definierenwith gr.Blocks() as demo:gr.Markdown("## Flux-Schnell Proxy\n""Leitet Anfragen an das offizielle „FLUX.1-schnell“-Space weiter und gibt das Bild zurück.")with gr.Row():with gr.Column():prompt = gr.Textbox(label="Prompt", placeholder="z.B. Ein futuristischer Cityscape …")5 unmodified lineswith gr.Column():output_img = gr.Image(label="Ergebnisbild")# 6. Event-Bindinggen_btn.click(fn=proxy_generate,inputs=[prompt, steps, scale, height, width],outputs=output_img)# 7. Gradio-Server als MCP-Server startendemo.launch(mcp_server=True)1234567891011121314151 unmodified line1718192021222324252627282930313233343536373839404142434445464748495051525354555 unmodified lines61626364656667686970717273import osimport gradio as grimport requestsimport base64from PIL import Imageimport io# 1. Konfiguration des Ziel-Space# Da das Space öffentlich ist, brauchen wir keinen HF_TOKEN.REMOTE_SPACE = "black-forest-labs/FLUX.1-schnell"# 2. REST-Endpunkt für Gradio-EmbedPREDICT_URL = f"https://hf.space/embed/{REMOTE_SPACE}/run/predict"def proxy_generate(prompt: str,num_inference_steps: int = 4,1 unmodified lineheight: int = 512,width: int = 512):"""Proxy-Funktion für FLUX.1-schnell via Gradio-REST-API:• prompt: Texteingabe für die Bildsynthese• num_inference_steps: Anzahl der Diffusionsschritte (Steps)• guidance_scale: CFG-Skalierungsfaktor (Scale)• height, width: Höhe/Breite des Ausgabebildes"""# 3. Payload für run/predict formen# Die Reihenfolge der Listenelemente muss exakt der Reihenfolge der Inputs im Space entsprechen:# [prompt, num_inference_steps, guidance_scale, height, width]payload = {"data": [prompt, num_inference_steps, guidance_scale, height, width]}# 4. API-Aufruf: POST ans Gradio-Embed-APIresponse = requests.post(PREDICT_URL, json=payload)response.raise_for_status()res_json = response.json()# 5. Aus dem JSON das Bild (Base64) extrahieren# Die Antwort sieht in etwa so aus: {"data": ["<base64-encoded-png-string>"], ...}data_list = res_json.get("data", [])if not data_list or not isinstance(data_list[0], str):raise ValueError(f"Unerwartetes Response-Format: {res_json}")base64_str = data_list[0]# 6. Base64 → Bytes decodieren → PIL.Imageimage_bytes = base64.b64decode(base64_str.split(",")[-1])image = Image.open(io.BytesIO(image_bytes))return image# 7. Gradio-Interface definierenwith gr.Blocks() as demo:gr.Markdown("## Flux-Schnell Proxy\n""Leitet Anfragen an das öffentliche „FLUX.1-schnell“-Space weiter und zeigt das Bild.")with gr.Row():with gr.Column():prompt = gr.Textbox(label="Prompt", placeholder="z.B. Ein futuristischer Cityscape …")5 unmodified lineswith gr.Column():output_img = gr.Image(label="Ergebnisbild")# 8. Event-Bindinggen_btn.click(fn=proxy_generate,inputs=[prompt, steps, scale, height, width],outputs=output_img)# 9. Gradio-Server als MCP-Server starten# Nun liefert Gradio automatisch:# • /gradio_api/mcp/schema → MCP-Schema deiner proxy_generate-Funktion# • /gradio_api/mcp/sse → SSE-Endpunkt für JSON-RPC-2.0-Aufrufedemo.launch(mcp_server=True)
app.py+34-41