File size: 8,062 Bytes
8bb99c4
d229ac5
d0ce3d8
8bb99c4
307a3fb
 
0339f03
d2e8e3d
 
 
 
 
 
 
ff2f8a3
 
 
 
 
8bb99c4
 
d0ce3d8
3af69cf
 
b502aea
 
3af69cf
b502aea
 
 
3af69cf
 
 
 
 
b502aea
3af69cf
 
 
 
d0ce3d8
 
 
 
 
 
 
87ab8f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1148bce
 
 
 
87ab8f9
d229ac5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7262a5b
8d7ebba
 
4adaee1
7c8381c
 
 
 
 
d229ac5
7c8381c
0e3ba22
 
7c8381c
 
 
87ab8f9
7262a5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307a3fb
 
7262a5b
 
 
307a3fb
0e3ba22
307a3fb
 
 
7262a5b
d229ac5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b2f0a4
 
 
e21102a
 
 
3b2f0a4
 
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
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 <https://icanhazdadjoke.com/> 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