Spaces:
Runtime error
Runtime error
Update app.py
Browse files1238 unmodified lines1213141516171819202122232425262728293031323334353637383930 unmodified lines707172737475762 unmodified lines79808182838485868788899091929394959614 unmodified lines11111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814 unmodified lines163164165166167168169170171172173174175import requestsimport jsonimport gradio as gr8 unmodified linestype: 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 one of: 'Any', 'Programming', 'Misc', 'Pun', 'Dark', 'Spooky', 'Christmas'.lang (str): Language code for the joke (e.g., 'pt' for Portuguese). Only use if the user requests another language.blacklistFlags (str | None): Comma-separated flags to exclude: 'nsfw', 'religious', 'political', 'racist', 'sexist', 'explicit'. Only use if requested.safe_mode (bool): Defaults to True. Set to False only if the user explicitly wants potentially unsafe jokes.type (str | None): 'single' or 'twopart'. Only set if user specifies.contains (str | None): A substring the joke must include. Only set if requested.idRange (str | None): Specific ID or range (e.g., '10-50'). Only use if requested.amount (int): Number of jokes to fetch (1–10). Only change if the user asks for multiple jokes.Returns:A string containing the joke.**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] = {30 unmodified linesif amount > 1:jokes = [extract(j) for j in data.get("jokes", [])]else:# single joke — flatten dict to string if neededsingle = extract(data)jokes = [single]2 unmodified linesexcept 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 analyze. Must not be empty.Returns:A JSON string with:- polarity: -1 (negative) to 1 (positive)- subjectivity: 0 (objective) to 1 (subjective)- assessment: 'positive', 'negative', or 'neutral'"""if not text:return json.dumps({"error": "Input text cannot be empty."})14 unmodified lines"assessment": assessment}, indent=2)# --- Gradio Interface Setup ---# Joke Generation interfacejoke_interface = gr.Interface(fn=joke_generation,inputs=[gr.Textbox(label="Categories",value="Any",info="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"]),gr.Checkbox(label="Safe Mode", value=True),gr.Radio(label="Joke Type",choices=["single", "twopart"]),gr.Textbox(label="Contains"),gr.Textbox(label="ID Range"),gr.Slider(label="Amount",minimum=1, maximum=10, step=1, value=1),],outputs=gr.JSON(),api_name="joke_generation",14 unmodified linesdescription="Analyzes the sentiment of a piece of text.")# Combine into a tabbed demodemo = gr.TabbedInterface([joke_interface, sentiment_interface],["Joke Generation", "Sentiment Analysis"])if __name__ == "__main__":demo.launch(mcp_server=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911928 unmodified lines20120220320420520620720820921030 unmodified lines2412422432442452462 unmodified lines24925025125225325425525625725814 unmodified lines27327427527627727827928028128228328428528628728828929014 unmodified lines305306307308309310311312# 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 one of: 'Any', 'Programming', 'Misc', 'Pun', 'Dark', 'Spooky', 'Christmas'.# lang (str): Language code for the joke (e.g., 'pt' for Portuguese). Only use if the user requests another language.# blacklistFlags (str | None): Comma-separated flags to exclude: 'nsfw', 'religious', 'political', 'racist', 'sexist', 'explicit'. Only use if requested.# safe_mode (bool): Defaults to True. Set to False only if the user explicitly wants potentially unsafe jokes.# type (str | None): 'single' or 'twopart'. Only set if user specifies.# contains (str | None): A substring the joke must include. Only set if requested.# idRange (str | None): Specific ID or range (e.g., '10-50'). Only use if requested.# amount (int): Number of jokes to fetch (1–10). Only change if the user asks for multiple jokes.# Returns:# A string containing the joke.# **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:# 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(item: dict):# if item.get("type") == "single":# return item["joke"]# else:# # two-part joke# return f"{item['setup']} {item['delivery']}"# if amount > 1:# jokes = [extract(j) for j in data.get("jokes", [])]# else:# # single joke — flatten dict to string if needed# single = extract(data)# 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.# Args:# text (str): The text to analyze. Must not be empty.# Returns:# A JSON string with:# - polarity: -1 (negative) to 1 (positive)# - subjectivity: 0 (objective) to 1 (subjective)# - assessment: 'positive', 'negative', or 'neutral'# """# if not text:# return json.dumps({"error": "Input text cannot be empty."})# blob = TextBlob(text)# polarity = round(blob.sentiment.polarity, 2)# subjectivity = round(blob.sentiment.subjectivity, 2)# if polarity > 0.1:# assessment = "positive"# elif polarity < -0.1:# assessment = "negative"# else:# assessment = "neutral"# return json.dumps({# "polarity": polarity,# "subjectivity": subjectivity,# "assessment": assessment# }, indent=2)# # --- Gradio Interface Setup ---# # Joke Generation interface# joke_interface = gr.Interface(# fn=joke_generation,# inputs=[# gr.Textbox(# label="Categories",# value="Any",# info="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"]# ),# gr.Checkbox(label="Safe Mode", value=True),# gr.Radio(# label="Joke Type",# choices=["single", "twopart"]# ),# gr.Textbox(label="Contains"),# gr.Textbox(label="ID Range"),# gr.Slider(# label="Amount",# minimum=1, maximum=10, step=1, value=1# ),# ],# 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."# )# )# # Sentiment Analysis interface# 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 into a tabbed demo# demo = gr.TabbedInterface(# [joke_interface, sentiment_interface],# ["Joke Generation", "Sentiment Analysis"]# )# if __name__ == "__main__":# demo.launch(mcp_server=True)###### Cursur version to see both tools# What’s changed?# Instead of gr.TabbedInterface, we use gr.Parallel, which exposes both interfaces as separate endpoints (and as separate tabs in the UI).# Each tool keeps its own api_name, so both /joke_generation and /sentiment_analysis endpoints will be available for API calls and for the UI.import requestsimport jsonimport gradio as gr8 unmodified linestype: str | None = None,contains: str | None = None,idRange: str | None = None,amount: int = 1,):"""Fetches jokes from JokeAPI."""url = f"https://v2.jokeapi.dev/joke/{categories}"params: dict[str, str | int | bool] = {30 unmodified linesif amount > 1:jokes = [extract(j) for j in data.get("jokes", [])]else:single = extract(data)jokes = [single]2 unmodified linesexcept 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."""if not text:return json.dumps({"error": "Input text cannot be empty."})14 unmodified lines"assessment": assessment}, indent=2)# Joke Generation interfacejoke_interface = gr.Interface(fn=joke_generation,inputs=[gr.Textbox(label="Categories", value="Any", info="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"]),gr.Checkbox(label="Safe Mode", value=True),gr.Radio(label="Joke Type", choices=["single", "twopart"]),gr.Textbox(label="Contains"),gr.Textbox(label="ID Range"),gr.Slider(label="Amount", minimum=1, maximum=10, step=1, value=1),],outputs=gr.JSON(),api_name="joke_generation",14 unmodified linesdescription="Analyzes the sentiment of a piece of text.")# Multi-endpoint setup using gr.Paralleldemo = gr.Parallel(joke_interface, sentiment_interface)if __name__ == "__main__":demo.launch(mcp_server=True)
app.py+198-61