Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| from fastapi import FastAPI | |
| from pydantic import BaseModel | |
| import uvicorn | |
| import json | |
| # --- Backend FastAPI (integrado no mesmo arquivo) --- | |
| class Item(BaseModel): | |
| name: str | |
| description: str | None = None | |
| price: float | |
| # Criamos as funções do backend como funções Python normais | |
| def root_message(): | |
| return {"message": "Hello World"} | |
| def hello_message(name: str): | |
| return {"message": f"Hello, {name.upper()}"} | |
| def create_item_backend(name: str, description: str | None = None, price: float = 0.0): | |
| item = Item(name=name, description=description, price=price) | |
| return item | |
| # --- Frontend Gradio --- | |
| def get_root_message(): | |
| """Chama a função do backend diretamente""" | |
| try: | |
| result = root_message() | |
| return result.get("message", "Resposta inesperada da API.") | |
| except Exception as e: | |
| return f"Erro: {e}" | |
| def get_hello_message(name): | |
| """Chama a função do backend diretamente""" | |
| if not name: | |
| return "Por favor, insira um nome." | |
| try: | |
| result = hello_message(name) | |
| return result.get("message", "Resposta inesperada da API.") | |
| except Exception as e: | |
| return f"Erro: {e}" | |
| def create_item(name, description, price): | |
| """Chama a função do backend diretamente""" | |
| if not name or price is None: | |
| return "Nome e Preço são campos obrigatórios." | |
| try: | |
| result = create_item_backend(name, description, price) | |
| # Converte o objeto Item para dict | |
| return { | |
| "name": result.name, | |
| "description": result.description, | |
| "price": result.price | |
| } | |
| except Exception as e: | |
| return f"Erro: {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 + FastAPI (Integrado)") | |
| # --- Para funcionar no Hugging Face Spaces --- | |
| if __name__ == "__main__": | |
| demo.launch() |