File size: 3,545 Bytes
89ecf4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import gradio as gr
from fastapi import FastAPI
from pydantic import BaseModel
import requests
import uvicorn
import os

# ==========================================
# KONFIGURATION FÜR HUGGING FACE
# ==========================================
# Hugging Face Spaces nutzt standardmäßig Port 7860. 
# Wir lesen den Port dynamisch aus den Umgebungsvariablen (Fallback auf 7860).
PORT = int(os.environ.get("PORT", 7860))

# ==========================================
# 1. FASTAPI SETUP (Das Backend)
# ==========================================

app = FastAPI(
    title="HF Space: Gradio & FastAPI Template",
    description="Ein Template für Hugging Face, das Gradio und FastAPI kombiniert."
)

class InputData(BaseModel):
    text: str

class OutputData(BaseModel):
    result: str
    length: int

@app.post("/api/process", response_model=OutputData)
def process_text(data: InputData):
    """
    Der FastAPI-Endpunkt. Hier läuft deine eigentliche Logik (z.B. KI-Modelle).
    """
    processed_text = f"Hallo vom HF-Backend! Du hast gesendet: '{data.text}'"
    text_length = len(data.text)
    return OutputData(result=processed_text, length=text_length)

# ==========================================
# 2. GRADIO FUNKTIONEN (Die API-Aufrufe)
# ==========================================

def call_fastapi(user_input: str) -> str:
    """
    Gradio ruft das eigene FastAPI-Backend über HTTP auf.
    Da beides im selben Hugging Face Container läuft, nutzen wir localhost (127.0.0.1) 
    und den dynamisch ermittelten Port.
    """
    api_url = f"http://127.0.0.1:{PORT}/api/process"
    payload = {"text": user_input}
    
    try:
        response = requests.post(api_url, json=payload, timeout=10)
        response.raise_for_status()
        data = response.json()
        return f"Ergebnis: {data['result']}\nZeichenanzahl: {data['length']}"
        
    except requests.exceptions.RequestException as e:
        return f"Fehler beim API-Aufruf auf Port {PORT}: {str(e)}"

# ==========================================
# 3. GRADIO UI SETUP (Das Frontend)
# ==========================================

with gr.Blocks(title="Mein HF FastAPI Client", theme=gr.themes.Soft()) as gradio_app:
    gr.Markdown("# 🚀 Hugging Face: Gradio + FastAPI Template")
    gr.Markdown("Diese UI sendet Anfragen an das integrierte FastAPI-Backend innerhalb des HF Spaces.")
    
    with gr.Row():
        with gr.Column():
            input_text = gr.Textbox(label="Deine Eingabe", placeholder="Schreibe hier etwas rein...", lines=3)
            submit_btn = gr.Button("An FastAPI senden", variant="primary")
            
        with gr.Column():
            output_text = gr.Textbox(label="Antwort von FastAPI", interactive=False, lines=3)
            
    submit_btn.click(
        fn=call_fastapi,
        inputs=input_text,
        outputs=output_text
    )

# ==========================================
# 4. APP MOUNTING & SERVER START
# ==========================================

# Wir mounten Gradio in FastAPI. Hugging Face sieht die Variable `app` 
# und startet sie automatisch richtig.
app = gr.mount_gradio_app(app, gradio_app, path="/")

if __name__ == "__main__":
    # Dieser Block wird nur ausgeführt, wenn du das Skript LOKAL auf deinem PC testest.
    # Auf Hugging Face übernimmt das System den Start.
    # WICHTIG: host="0.0.0.0" erlaubt externe Zugriffe (nötig für Docker/HF Spaces).
    print(f"Starte Server lokal... Öffne http://127.0.0.1:{PORT} in deinem Browser.")
    uvicorn.run(app, host="0.0.0.0", port=PORT)