import gradio as gr import json import requests import flux def greet(name: str) -> str: """ Greets the user with a personalized hello message. Args: name (str): The name of the user to greet. Returns: str: A greeting message addressed to the specified user. """ if not name: return "Hello stranger!!" name = name.strip() if len(name) > 50: return "Name is too long!" return "Hello " + name + "!!" def get_dad_joke(): """ Fetches a random dad joke from the icanhazdadjoke.com API. The function makes an HTTP GET request to the API with appropriate headers to receive JSON response. Args: None Returns: str: A random dad joke if successful, otherwise returns an error message. - Success: Returns the joke text - Failure: Returns "Failed to retrieve a joke." if the API request fails - No joke: Returns "No joke found." if the API response doesn't contain a joke Requires: requests: The requests library must be imported to make HTTP requests """ headers = {"Accept": "application/json"} response = requests.get("https://icanhazdadjoke.com/", headers=headers) if response.status_code == 200: data = response.json() return data.get("joke", "No joke found.") else: return "Failed to retrieve a joke." def calculate(n1, op, n2): """ Performs basic arithmetic operations between two numbers. This function takes two numbers and an operator as input and returns the result of the arithmetic operation. Supported operations are addition (+), subtraction (-), multiplication (*), and division (/). For division, checks for division by zero. Args: n1 (float): First number op (str): Operator ('+', '-', '*', or '/') n2 (float): Second number Returns: float: Result of the arithmetic operation if valid str: "Error" if invalid operation (like division by zero) Examples: >>> calculate(10, "+", 5) 15 >>> calculate(10, "/", 0) "Error" """ if op == "+": return str(n1 + n2) if op == "-": return str(n1 - n2) if op == "*": return str(n1 * n2) if op == "/" and n2 != 0: return str(n1 / n2) return "Error" BASE_GOOGLE_BOOKS_VOLUMES_API = "https://www.googleapis.com/books/v1/volumes" def get_google_book_filtered(title="", author="", genre="", isbn=""): """ Get a filtered list of books from Google Books API. It can be filtered by title, author, genre, and ISBN. Results are ordered by relevance to the query. Only a subset of the volume info is included. Only 10 results are returned. Args: title: str - title of the book author: str - author of the book genre: str - genre of the book isbn: str - ISBN of the book Returns: list - list of books """ query = "q=" if title: query += f"intitle:{title}" if author: query += f"+inauthor:{author}" if genre: query += f"+subject:{genre}" if isbn: query += f"+isbn:{isbn}" if query != "q=": url = f"{BASE_GOOGLE_BOOKS_VOLUMES_API}?{query}" url += "&orderBy=relevance" url += "&maxResults=10" url += "&projection=lite" # only include a subset of the volume info json_res = requests.get(url).json() return json.dumps(json_res, indent=2) def get_google_books_book_by_id(book_id): """ Get a book from Google Books API by its ID. Args: book_id: str - ID of the book Returns: dict - book """ url = f"{BASE_GOOGLE_BOOKS_VOLUMES_API}/{book_id}?projection=full" json_res = requests.get(url).json() return json.dumps(json_res, indent=2) print(f"DEBUG: Gradio version={gr. __version__}") with gr.Blocks() as demo: gr.Markdown( """## 🧮Calculator and other useful tools ### Built from the ground up for LLMs This app provides a simple calculator, a dad joke generator, a greeting function, an image generation feature and a Google Books API integration. Read the [project documentation](https://huggingface.co/spaces/Agents-MCP-Hackathon/simple-calculator/blob/main/README.md) to understand its background and motivations. Use via API or MCP 🚀 · [Powered by Modal](https://modal.com/) · [Built with Gradio](https://www.gradio.app/) 🟧 """ ) tab_calc = gr.Tab("Calculator") with tab_calc: with gr.Row(): num1 = gr.Number(label="First Number") operation = gr.Dropdown( choices=["+", "-", "*", "/"], label="Operation" ) num2 = gr.Number(label="Second Number") calc_btn = gr.Button("Calculate") calc_output = gr.Text(label="Result") calc_btn.click( fn=calculate, inputs=[num1, operation, num2], outputs=calc_output, api_name="calculate") tab_joke = gr.Tab("Dad Joke") with tab_joke: joke_btn = gr.Button("Get Dad Joke") joke_output = gr.Textbox(label="Dad Joke") joke_btn.click(fn=get_dad_joke, outputs=joke_output, api_name="get_dad_joke") tab_greet = gr.Tab("Greet") with tab_greet: name = gr.Textbox(label="Type your name", placeholder="Enter your name here") greet_btn = gr.Button("Greet") output = gr.Textbox(label="Message") greet_btn.click(fn=greet, inputs=name, outputs=output, api_name="greet") # Generate an image tab_image = gr.Tab("Image Generation") with tab_image: img_prompt = gr.Textbox( label="Image Prompt", placeholder="Enter a prompt for the image generation", value="A portrait of a handsome software developer" ) img_btn = gr.Button("Generate Image") img_output = gr.Image(label="Sample Image") img_btn.click( fn=flux.generate_image2, # Choose 1 or 2 inputs=img_prompt, outputs=img_output, api_name="generate_image") tab_GB_search = gr.Tab("Google Books - Search") with tab_GB_search: with gr.Row(): title_textbox = gr.Textbox( label="Title", placeholder="Filter by title", ) author_textbox = gr.Textbox( label="Author", placeholder="Filter by author", ) with gr.Row(): genre_textbox = gr.Textbox( label="Genre", placeholder="Filter by genre", ) isbn_textbox = gr.Textbox( label="ISBN", placeholder="Filter by ISBN", ) with gr.Row(): search_btn = gr.Button("Search Books") with gr.Row(): output_books_box = gr.Textbox(label="Results") search_btn.click( fn=get_google_book_filtered, inputs=[title_textbox, author_textbox, genre_textbox, isbn_textbox], outputs=output_books_box, api_name="google_books_search", ) tab_GB_get_by_id = gr.Tab("Google Books - Get Book By ID") with tab_GB_get_by_id: with gr.Row(): id_textbox = gr.Textbox( label="ID", placeholder="Book ID", ) search_btn = gr.Button("Get Book") with gr.Row(): output_book_box = gr.Textbox(label="Results") search_btn.click( fn=get_google_books_book_by_id, inputs=[id_textbox], outputs=output_book_box, api_name="google_books_get_by_id", ) demo.launch( mcp_server=True, share=True, ssr_mode=False, server_name="0.0.0.0", # Listen on all interfaces server_port=7860) # Use the port we exposed in Dockerfile # EOF