Spaces:
Runtime error
Runtime error
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633770 unmodified lines408409410411412413414415416417# 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)# GEMINI# import requests# import json# import gradio as gr# from textblob import TextBlob# # Tool 1: Joke Generation# def joke_generation(# categories: str = "Any",# lang: str = "en",# blacklistFlags: str | None = None,# safe_mode: bool = True,# type: str | None = None,# contains: str | None = None,# idRange: str | None = None,# amount: int = 1# ):# """# Fetches jokes from JokeAPI. Use this tool when the user asks for a joke.# **IMPORTANT:** For simple requests like "tell me a joke", you do not need to specify any parameters. The function will automatically fetch a safe, general joke by default.# Args:# categories (str): The category of the joke. ONLY use this if the user explicitly asks for a specific category. It MUST be a string from: 'Any', 'Programming', 'Misc', 'Pun', 'Dark', 'Spooky', 'Christmas'. If the user's category isn't in this list, default to 'Any'.# lang (str): The language code for the joke (e.g., 'pt' for Portuguese). Only use if the user requests a language other than English.# blacklistFlags (str | None): A comma-separated string of flags to exclude certain joke types: 'nsfw', 'religious', 'political', 'racist', 'sexist', 'explicit'. Only use if the user makes a specific exclusion request.# safe_mode (bool): Defaults to True. Set to False only if the user explicitly asks for potentially unsafe jokes.# type (str | None): Can be 'single' or 'twopart'. Only use if the user specifies a preference for a one-liner or a setup/delivery joke.# contains (str | None): A string that MUST be present in the joke. Only use if the user asks for a joke containing a specific word.# idRange (str | None): A specific ID or a range of IDs for jokes. Do not use unless specifically requested.# amount (int): The number of jokes to fetch (1-10). Only change this if the user asks for more than one joke.# Returns:# A list of joke strings. If amount=1, returns a list with a single string; if amount>1, returns multiple strings.# **Example:**# >>> joke_generation()# ["Why don't scientists trust atoms? Because they make up everything!"]# """# url = f"https://v2.jokeapi.dev/joke/{categories}"# 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"] = ""# if type:# params["type"] = type# if contains:# params["contains"] = contains# if idRange:# params["idRange"] = idRange# try:# resp = requests.get(url, params=params)# resp.raise_for_status()# data = resp.json()# if data.get("error"):# return [f"JokeAPI error: {data.get('message', 'Unknown error')}" ]# def extract(j: dict):# return j["joke"] if j.get("type") == "single" else {"setup": j["setup"], "delivery": j["delivery"]}# # Normalize output and flatten single-part dictionaries# jokes = []# if amount > 1:# jokes = [extract(j) for j in data.get("jokes", [])]# else:# single = extract(data)# if isinstance(single, dict):# # flatten to a single string# single = f"{single['setup']} {single['delivery']}"# jokes = [single]# return jokes# except requests.exceptions.RequestException as e:# return [f"Network error: {e}"]# # Tool 2: Sentiment Analysis# def sentiment_analysis(text: str) -> str:# """# Analyzes the sentiment of a given text using TextBlob. Use this to determine if a text is positive, negative, or neutral.# Args:# text (str): The text to be analyzed. Must not be empty.# 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.sentiment# result = {# "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 tool# joke_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. For a simple joke, just click Submit without changing any fields."# )# # Define the interface for the Sentiment Analysis tool# sentiment_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 demo# demo = gr.TabbedInterface(# [joke_interface, sentiment_interface],# ["Joke Generation", "Sentiment Analysis"]# )# # Launch the interface and MCP server# if __name__ == "__main__":# demo.launch(mcp_server=True)## CHATGPTimport requestsimport jsonimport gradio as gr70 unmodified linessingle = extract(data)jokes = [single]# return jokes# Just a test:return ["I'm not saying my son is ugly... But on Halloween he went to tell the neighbors to turn down their TV and they gave him some candy."]except requests.exceptions.RequestException as e:return [f"Network error: {e}"]12370 unmodified lines74757677787980import requestsimport jsonimport gradio as gr70 unmodified linessingle = extract(data)jokes = [single]return jokesexcept requests.exceptions.RequestException as e:return [f"Network error: {e}"]
app.py+1-338