Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234567891011123 unmodified lines16171819202122232425262728293031323334353637383940414243444546474849501 unmodified line525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156import requestsimport jsonimport gradio as grfrom textblob import TextBlob# Create a Joke API fetch tooldef joke_generation(categories: str = "Any",format: str = "json",lang: str = "en",blacklistFlags: str | None = None,safe_mode: bool = False,3 unmodified linesamount: 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"] = blacklistFlagsif safe_mode:params["safe-mode"] = ""if type:params["type"] = typeif contains:1 unmodified lineif idRange:params["idRange"] = idRangeresp = 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 jokesif amount > 1:return [extract(j) for j in data["jokes"]]# single jokereturn extract(data)# Create a sentiment analysis tooldef sentiment_analysis(text: str) -> str:"""Analyze the sentiment of the given text.Args:text (str): The text to analyzeReturns:str: A JSON string containing polarity, subjectivity, and assessment"""blob = TextBlob(text)sentiment = blob.sentimentresult = {"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 serverif __name__ == "__main__":1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761773 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032042052062072082091 unmodified line211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318# 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# Tool 1: Joke Generationdef joke_generation(categories: str = "Any",lang: str = "en",blacklistFlags: str | None = None,safe_mode: bool = False,3 unmodified linesamount: int = 1):"""Fetches jokes from JokeAPI (https://sv443.net/jokeapi/v2/).Args: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: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)."""# 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 | bool] = {"format": "json", "lang": lang, "amount": amount}if blacklistFlags:params["blacklistFlags"] = blacklistFlagsif safe_mode:# The API expects the key to be present for safe mode, value doesn't matterparams["safe-mode"] = ""if type:params["type"] = typeif contains:1 unmodified lineif idRange:params["idRange"] = idRangetry: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 outputreturn [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"]}# API returns a 'jokes' list for amount > 1, and a single object for amount == 1if amount > 1:return [extract(j) for j in data.get("jokes", [])]else:return [extract(data)]except requests.exceptions.RequestException as e:return [f"Network error: {e}"]# Tool 2: Sentiment Analysisdef sentiment_analysis(text: str) -> str:"""Analyzes the sentiment of a given text using TextBlob.Args:text (str): The text to be analyzed.Returns: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.sentimentresult = {"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, indent=2)# --- Gradio Interface Setup ---# Define the interface for the Joke Generation tooljoke_interface = gr.Interface(fn=joke_generation,inputs=[gr.Textbox(label="Categories",value="Any",info="Comma-separated list: Any, Programming, Misc, Pun, Dark, Spooky, Christmas"),gr.Dropdown(label="Language",choices=["en", "cs", "de", "es", "fr", "pt"],value="en"),gr.CheckboxGroup(label="Blacklist Flags",choices=["nsfw", "religious", "political", "racist", "sexist", "explicit"],info="Exclude jokes with these flags."),gr.Checkbox(label="Safe Mode", value=True, info="Filter for safe jokes."),gr.Radio(label="Joke Type",choices=["single", "twopart"],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",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 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