Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171617217317491751761773 unmodified lines181182183192021221841852425262728293031323318618718818919019119219319435363719519639404119719819943200201202203204205472062072082091 unmodified line211212213214555657585921521621721821922022122261622232242256465662262272282292302316869232233234235722362372387576239240787924124281243244245246247248249250251878889252253254255256922572582599596979899100101102260261104262263264265266108109267268269270271112113114115272273274275117118119120276277278279280122123124125126127128281282130283284132133134135136137138139140285286287288289143290291145292293294295296150151297298299300301302303304305306307308309310311312313314315316317318# import requests# import json# import gradio as gr# from textblob import TextBlob
# # Create a Joke API fetch tool# def joke_generation(# categories: str = "Any",# format: str = "json",# lang: str = "en",# blacklistFlags: str | None = None,# safe_mode: bool = False,# type: str | None = None,# contains: str | None = None,# idRange: str | None = None,# amount: int = 1# ):# """# Fetch jokes from JokeAPI (https://sv443.net/jokeapi/v2/).
# Defaults to one random joke from Any category, English, JSON.
# Args:# - categories (str): Comma-separated list from [Any, Programming, Misc, Pun, Dark, Spooky, Christmas]. If you are asked a joke category that doesn't macht any of the categories from the previous list you must ignore this tool and come up with your own joke.# - format (str): Must be 'json'. (JokeAPI also supports xml, yaml, txt, but we only parse JSON here.)# - lang (str): ISO 639-1 code for language of the joke. Defaults to 'en'. If you are asked a joke in portuguese, please set this parameter as 'pt' when calling function.# - blacklistFlags (str|None): Comma-separated flags to exclude: nsfw, religious, political, racist, sexist, explicit.# - safe_mode (bool): If True, enables `safe-mode` filter to remove all potentially unsafe jokes.# - type (str|None): If given, either 'single' (one-liner) or 'twopart' (setup + delivery).# - contains (str|None): Case-insensitive substring that must appear in the joke text.# - idRange (str|None): A single ID or range (e.g. "10-50") to limit by JokeAPI’s internal IDs.# - amount (int): How many jokes to fetch (1–10). Defaults to 1.
# Returns:# - If amount == 1 and type == 'single': returns the joke text (str).# - If amount == 1 and type == 'twopart': returns a dict {"setup":…, "delivery":…}.# - If amount > 1: returns a list of those results (each either str or {"setup","delivery"}).# """# if format != "json":# raise ValueError("joke_generation only supports JSON format.")
# url = f"https://v2.jokeapi.dev/joke/{categories}"# params: dict[str, str | int] = {"format": "json", "lang": lang, "amount": amount}# if blacklistFlags:# params["blacklistFlags"] = blacklistFlags# if safe_mode:# params["safe-mode"] = ""# if type:# params["type"] = type# if contains:# params["contains"] = contains# if idRange:# params["idRange"] = idRange
# resp = requests.get(url, params=params)# resp.raise_for_status()# data = resp.json()# if data.get("error"):# raise ValueError(f"JokeAPI error: {data.get('message','Unknown error')}")
# def extract(j: dict):# return j["joke"] if j["type"] == "single" else {"setup": j["setup"], "delivery": j["delivery"]}
# # multiple jokes# if amount > 1:# return [extract(j) for j in data["jokes"]]
# # single joke# return extract(data)
# # Create a sentiment analysis tool# def sentiment_analysis(text: str) -> str:# """# Analyze the sentiment of the given text.
# Args:# text (str): The text to analyze
# Returns:# str: A JSON string containing polarity, subjectivity, and assessment# """# blob = TextBlob(text)# sentiment = blob.sentiment
# result = {# "polarity": round(sentiment.polarity, 2), # -1 (negative) to 1 (positive)# "subjectivity": round(sentiment.subjectivity, 2), # 0 (objective) to 1 (subjective)# "assessment": "positive" if sentiment.polarity > 0 else "negative" if sentiment.polarity < 0 else "neutral"# }
# return json.dumps(result)
# # Create the Gradio interface (creates both the web UI and MCP server)# # demo = gr.Interface(# # fn=joke_generation,# # inputs=gr.Textbox(placeholder="Enter text to analyze..."),# # outputs=gr.Textbox(), # Changed from gr.JSON() to gr.Textbox()# # title="Text Sentiment Analysis",# # description="Analyze the sentiment of text using TextBlob"# # )
# demo = gr.Interface(# fn=joke_generation,# inputs=[# gr.Textbox(# label="categories",# info="Comma-separated list from [Any, Programming, Misc, Pun, Dark, Spooky, Christmas]"# ),# gr.Dropdown(# label="format",# choices=["json"],# value="json",# info="Must be 'json'"# ),# gr.Textbox(# label="lang",# value="en",# info="ISO 639-1 code for the joke’s language"# ),# # just remove optional=True here:# gr.Textbox(# label="blacklistFlags",# info="Comma-separated flags to exclude: nsfw, religious, political, racist, sexist, explicit"# ),# gr.Checkbox(label="safe_mode", info="Enable safe-mode filter"),# # and here:# gr.Radio(# label="type",# choices=["single", "twopart"],# info="If given: 'single' (one-liner) or 'twopart' (setup + delivery)"# ),# gr.Textbox(# label="contains",# info="Case-insensitive substring that must appear in the joke text"# ),# gr.Textbox(# label="idRange",# info="A single ID or range (e.g. '10-50')"# ),# gr.Slider(# label="amount",# minimum=1, maximum=10, step=1, value=1,# info="How many jokes to fetch (1–10)"# ),# ],# outputs=gr.JSON(),# api_name="joke_generation",# title="Joke Generation",# description="Fetch jokes from JokeAPI with all available parameters."# )
# # Launch the interface and MCP server# if __name__ == "__main__":# demo.launch(mcp_server=True)
# GEMINIimport requestsimport jsonimport gradio as grfrom textblob import TextBlob
# Create a Joke API fetch tool# Tool 1: Joke Generationdef joke_generation( categories: str = "Any", format: str = "json", lang: str = "en", blacklistFlags: str | None = None, safe_mode: bool = False,3 unmodified lines amount: int = 1): """ Fetch jokes from JokeAPI (https://sv443.net/jokeapi/v2/).
Defaults to one random joke from Any category, English, JSON.
Fetches jokes from JokeAPI (https://sv443.net/jokeapi/v2/). Args: - categories (str): Comma-separated list from [Any, Programming, Misc, Pun, Dark, Spooky, Christmas]. If you are asked a joke category that doesn't macht any of the categories from the previous list you must ignore this tool and come up with your own joke. - format (str): Must be 'json'. (JokeAPI also supports xml, yaml, txt, but we only parse JSON here.) - lang (str): ISO 639-1 code for language of the joke. Defaults to 'en'. If you are asked a joke in portuguese, please set this parameter as 'pt' when calling function. - blacklistFlags (str|None): Comma-separated flags to exclude: nsfw, religious, political, racist, sexist, explicit. - safe_mode (bool): If True, enables `safe-mode` filter to remove all potentially unsafe jokes. - type (str|None): If given, either 'single' (one-liner) or 'twopart' (setup + delivery). - contains (str|None): Case-insensitive substring that must appear in the joke text. - idRange (str|None): A single ID or range (e.g. "10-50") to limit by JokeAPI’s internal IDs. - amount (int): How many jokes to fetch (1–10). Defaults to 1.
categories (str): A comma-separated list of categories. Valid options are: Any, Programming, Misc, Pun, Dark, Spooky, Christmas. lang (str): The language code for the joke (e.g., 'en', 'de', 'pt'). Defaults to 'en'. blacklistFlags (str | None): Comma-separated flags to exclude jokes. Valid options: nsfw, religious, political, racist, sexist, explicit. safe_mode (bool): If True, enables `safe-mode` to filter out potentially unsafe jokes. type (str | None): The type of joke. Can be 'single' for a one-liner or 'twopart' for a setup and delivery format. contains (str | None): A case-insensitive string that must be present in the joke. idRange (str | None): A specific ID or a range of IDs (e.g., "10-50") to fetch. amount (int): The number of jokes to fetch, from 1 to 10. Returns: - If amount == 1 and type == 'single': returns the joke text (str). - If amount == 1 and type == 'twopart': returns a dict {"setup":…, "delivery":…}. - If amount > 1: returns a list of those results (each either str or {"setup","delivery"}). A list of jokes. Each joke is either a string (for single-part jokes) or a dictionary with "setup" and "delivery" keys (for two-part jokes). """ if format != "json": raise ValueError("joke_generation only supports JSON format.")
# The 'format' parameter is hardcoded to 'json' as it's the only one we parse. # It's removed from the function signature to avoid user confusion in the UI. url = f"https://v2.jokeapi.dev/joke/{categories}" params: dict[str, str | int] = {"format": "json", "lang": lang, "amount": amount} params: dict[str, str | int | bool] = {"format": "json", "lang": lang, "amount": amount} if blacklistFlags: params["blacklistFlags"] = blacklistFlags if safe_mode: # The API expects the key to be present for safe mode, value doesn't matter params["safe-mode"] = "" params["safe-mode"] = "" if type: params["type"] = type if contains:1 unmodified line if idRange: params["idRange"] = idRange
try: resp = requests.get(url, params=params) resp.raise_for_status() data = resp.json() if data.get("error"): raise ValueError(f"JokeAPI error: {data.get('message','Unknown error')}") resp = requests.get(url, params=params) resp.raise_for_status() data = resp.json()
if data.get("error"): # Return the error message as a string in a list to be displayed in the JSON output return [f"JokeAPI error: {data.get('message', 'Unknown error')}"]
def extract(j: dict): return j["joke"] if j["type"] == "single" else {"setup": j["setup"], "delivery": j["delivery"]} def extract(j: dict): return j["joke"] if j["type"] == "single" else {"setup": j["setup"], "delivery": j["delivery"]}
# multiple jokes if amount > 1: return [extract(j) for j in data["jokes"]] # API returns a 'jokes' list for amount > 1, and a single object for amount == 1 if amount > 1: return [extract(j) for j in data.get("jokes", [])] else: return [extract(data)]
# single joke return extract(data) except requests.exceptions.RequestException as e: return [f"Network error: {e}"]
# Create a sentiment analysis tool# Tool 2: Sentiment Analysisdef sentiment_analysis(text: str) -> str: """ Analyze the sentiment of the given text.
Analyzes the sentiment of a given text using TextBlob. Args: text (str): The text to analyze
text (str): The text to be analyzed. Returns: str: A JSON string containing polarity, subjectivity, and assessment A JSON string containing the polarity, subjectivity, and a simple assessment ('positive', 'negative', or 'neutral'). """ if not text: return json.dumps({"error": "Input text cannot be empty."}) blob = TextBlob(text) sentiment = blob.sentiment
result = { "polarity": round(sentiment.polarity, 2), # -1 (negative) to 1 (positive) "subjectivity": round(sentiment.subjectivity, 2), # 0 (objective) to 1 (subjective) "assessment": "positive" if sentiment.polarity > 0 else "negative" if sentiment.polarity < 0 else "neutral" "polarity": round(sentiment.polarity, 2), # Range: -1 (negative) to 1 (positive) "subjectivity": round(sentiment.subjectivity, 2), # Range: 0 (objective) to 1 (subjective) "assessment": "positive" if sentiment.polarity > 0.1 else "negative" if sentiment.polarity < -0.1 else "neutral" }
return json.dumps(result) return json.dumps(result, indent=2)
# Create the Gradio interface (creates both the web UI and MCP server)# demo = gr.Interface(# fn=joke_generation,# inputs=gr.Textbox(placeholder="Enter text to analyze..."),# outputs=gr.Textbox(), # Changed from gr.JSON() to gr.Textbox()# title="Text Sentiment Analysis",# description="Analyze the sentiment of text using TextBlob"# )# --- Gradio Interface Setup ---
demo = gr.Interface(# Define the interface for the Joke Generation tooljoke_interface = gr.Interface( fn=joke_generation, inputs=[ gr.Textbox( label="categories", info="Comma-separated list from [Any, Programming, Misc, Pun, Dark, Spooky, Christmas]" label="Categories", value="Any", info="Comma-separated list: Any, Programming, Misc, Pun, Dark, Spooky, Christmas" ), gr.Dropdown( label="format", choices=["json"], value="json", info="Must be 'json'" label="Language", choices=["en", "cs", "de", "es", "fr", "pt"], value="en" ), gr.Textbox( label="lang", value="en", info="ISO 639-1 code for the joke’s language" gr.CheckboxGroup( label="Blacklist Flags", choices=["nsfw", "religious", "political", "racist", "sexist", "explicit"], info="Exclude jokes with these flags." ), # just remove optional=True here: gr.Textbox( label="blacklistFlags", info="Comma-separated flags to exclude: nsfw, religious, political, racist, sexist, explicit" ), gr.Checkbox(label="safe_mode", info="Enable safe-mode filter"), # and here: gr.Checkbox(label="Safe Mode", value=True, info="Filter for safe jokes."), gr.Radio( label="type", label="Joke Type", choices=["single", "twopart"], info="If given: 'single' (one-liner) or 'twopart' (setup + delivery)" ), gr.Textbox( label="contains", info="Case-insensitive substring that must appear in the joke text" ), gr.Textbox( label="idRange", info="A single ID or range (e.g. '10-50')" info="Filter by one-liner or setup/delivery." ), gr.Textbox(label="Contains", info="Joke must contain this text (case-insensitive)."), gr.Textbox(label="ID Range", info="Fetch a specific ID or range (e.g., '10-50')."), gr.Slider( label="amount", label="Amount", minimum=1, maximum=10, step=1, value=1, info="How many jokes to fetch (1–10)" info="How many jokes to fetch (1–10)." ), ], outputs=gr.JSON(), api_name="joke_generation", title="Joke Generation", description="Fetch jokes from JokeAPI with all available parameters." title="Joke Generation Tool", description="Fetches jokes from JokeAPI using various filters.")
# Define the interface for the Sentiment Analysis toolsentiment_interface = gr.Interface( fn=sentiment_analysis, inputs=gr.Textbox(lines=5, placeholder="Enter text here..."), outputs=gr.JSON(), api_name="sentiment_analysis", title="Sentiment Analysis Tool", description="Analyzes the sentiment of a piece of text.")
# Combine the interfaces into a single tabbed demodemo = gr.TabbedInterface( [joke_interface, sentiment_interface], ["Joke Generation", "Sentiment Analysis"])
# Launch the interface and MCP serverif __name__ == "__main__":app.py+248-86