Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import requests | |
| from fastapi import FastAPI | |
| from pydantic import BaseModel | |
| from typing import Optional | |
| # URL do nosso backend FastAPI. | |
| # Usamos 127.0.0.1 (localhost) porque ambos os processos rodarão na mesma máquina/container. | |
| BACKEND_URL = "http://127.0.0.1:8000" | |
| # --- Backend FastAPI --- | |
| app = FastAPI() | |
| class Item(BaseModel): | |
| name: str | |
| description: Optional[str] = None | |
| price: float | |
| def read_root(): | |
| return {"message": "Olá do Backend FastAPI!"} | |
| def read_hello(name: str): | |
| return {"message": f"Olá, {name}! Bem-vindo(a)!"} | |
| def create_api_item(item: Item): | |
| return item | |
| # --- Frontend Gradio --- | |
| def get_root_message(): | |
| """Chama o endpoint GET / via HTTP""" | |
| try: | |
| response = requests.get(f"{BACKEND_URL}/") | |
| response.raise_for_status() # Lança um erro para códigos de status 4xx/5xx | |
| return response.json().get("message", "Resposta inesperada da API.") | |
| except Exception as e: | |
| return f"Erro ao chamar a API: {e}" | |
| def get_hello_message(name): | |
| """Chama o endpoint GET /hello/{name} via HTTP""" | |
| if not name: | |
| return "Por favor, insira um nome." | |
| try: | |
| response = requests.get(f"{BACKEND_URL}/hello/{name}") | |
| response.raise_for_status() | |
| return response.json().get("message", "Resposta inesperada da API.") | |
| except Exception as e: | |
| return f"Erro ao chamar a API: {e}" | |
| def create_item(name, description, price): | |
| """Chama o endpoint POST /items/ via HTTP""" | |
| if not name or price is None: | |
| return "Nome e Preço são campos obrigatórios." | |
| item_data = { | |
| "name": name, | |
| "description": description, | |
| "price": price | |
| } | |
| try: | |
| response = requests.post(f"{BACKEND_URL}/items/", json=item_data) | |
| response.raise_for_status() | |
| return response.json() | |
| except Exception as e: | |
| return f"Erro ao chamar a API: {e}" | |
| # --- Interface Gradio --- | |
| with gr.Blocks(title="FastAPI + Gradio Integrado") as demo: | |
| gr.Markdown("# 🚀 FastAPI + Gradio Integrado") | |
| gr.Markdown("**Backend e Frontend em um único app!**") | |
| with gr.Tab("🏠 Saudação Raiz"): | |
| gr.Markdown("### Endpoint: GET /") | |
| btn_root = gr.Button("Chamar API Raiz", variant="primary") | |
| output_root = gr.Textbox( | |
| label="Resposta da API", | |
| placeholder="Clique no botão para ver a mensagem...", | |
| lines=3 | |
| ) | |
| btn_root.click(fn=get_root_message, inputs=None, outputs=output_root) | |
| with gr.Tab("👋 Saudação com Nome"): | |
| gr.Markdown("### Endpoint: GET /hello/{name}") | |
| with gr.Row(): | |
| with gr.Column(): | |
| input_name = gr.Textbox( | |
| label="Digite seu nome", | |
| placeholder="Seu nome aqui..." | |
| ) | |
| btn_hello = gr.Button("Enviar Saudação", variant="primary") | |
| with gr.Column(): | |
| output_hello = gr.Textbox( | |
| label="Resposta da API", | |
| lines=3 | |
| ) | |
| btn_hello.click(fn=get_hello_message, inputs=input_name, outputs=output_hello) | |
| with gr.Tab("📦 Criar Item"): | |
| gr.Markdown("### Endpoint: POST /items/") | |
| with gr.Row(): | |
| with gr.Column(): | |
| input_item_name = gr.Textbox( | |
| label="Nome do Item*", | |
| placeholder="Nome do item..." | |
| ) | |
| input_item_desc = gr.Textbox( | |
| label="Descrição do Item (Opcional)", | |
| placeholder="Descrição do item...", | |
| lines=2 | |
| ) | |
| input_item_price = gr.Number( | |
| label="Preço do Item*", | |
| value=0.0 | |
| ) | |
| btn_create = gr.Button("Criar Item", variant="primary") | |
| with gr.Column(): | |
| output_item = gr.JSON( | |
| label="Item Criado (Resposta da API)" | |
| ) | |
| btn_create.click( | |
| fn=create_item, | |
| inputs=[input_item_name, input_item_desc, input_item_price], | |
| outputs=output_item | |
| ) | |
| # Rodapé | |
| gr.Markdown("---") | |
| gr.Markdown("### 🔧 Desenvolvido com Gradio (Frontend) + FastAPI (Backend)") | |
| # Monta a interface Gradio na aplicação FastAPI. | |
| # A plataforma do Hugging Face Spaces detectará o objeto 'app' e o executará com um servidor ASGI (Uvicorn). | |
| app = gr.mount_gradio_app(app, demo, path="/") |