Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456721 unmodified lines293031323334353637383924 unmodified lines6465666768697071727374757677785 unmodified lines848586878889909120 unmodified lines1121131141151161171181195 unmodified lines12512612712812913013133 unmodified lines1651661671681691701711721731741755 unmodified lines181182183184import requestsimport jsonimport gradio as grfrom textblob import TextBlob# Tool 1: Joke Generationdef joke_generation(21 unmodified linesamount (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] = {24 unmodified linesif item.get("type") == "single":return item["joke"]else:# two-part jokereturn 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 neededsingle = extract(data)jokes = [single]return jokes5 unmodified linesdef 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)20 unmodified lines}, indent=2)# --- Gradio Interface Setup ---# Sentiment Analysis interfacesentiment_interface = gr.Interface(5 unmodified linesdescription="Analyzes the sentiment of a piece of text.")# Joke Generation interfacejoke_interface = gr.Interface(fn=joke_generation,33 unmodified lines))# Combine into a tabbed demodemo = gr.TabbedInterface([joke_interface, sentiment_interface],["Joke Generation", "Sentiment Analysis"])if __name__ == "__main__":5 unmodified lines12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719821 unmodified lines22022122222322422522624 unmodified lines2512522532542552562572582592602612625 unmodified lines26826927027127227327427527627720 unmodified lines2982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323335 unmodified lines33934034134234334433 unmodified lines3783793803813823833843853863873883893903913923933943953963975 unmodified lines403404405# 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 ---# # 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."# )# # 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."# )# )# # Combine into a tabbed demo# demo = gr.TabbedInterface(# [joke_interface, sentiment_interface],# ["Joke Generation", "Sentiment Analysis"]# )# if __name__ == "__main__":# demo.launch(mcp_server=True)import os# from dotenv import load_dotenvimport requestsimport jsonimport gradio as grfrom textblob import TextBlobfrom groq import Groq# Load environment (e.g. GROQ_API_KEY) from .env or Secrets in Hugging Face Spaces# load_dotenv()# In Hugging Face, go to Settings → Secrets & Variables → Add new variable:# Name: GROQ_API_KEY# Value: <your key># Tool 1: Joke Generationdef joke_generation(21 unmodified linesamount (int): Number of jokes to fetch (1–10). Only change if the user asks for multiple jokes.Returns:A list of jokes (as strings)."""url = f"https://v2.jokeapi.dev/joke/{categories}"params: dict[str, str | int | bool] = {24 unmodified linesif item.get("type") == "single":return item["joke"]else:return f"{item['setup']} {item['delivery']}"if amount > 1:jokes = [extract(j) for j in data.get("jokes", [])]else:jokes = [extract(data)]return jokes5 unmodified linesdef 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)20 unmodified lines}, indent=2)# Tool 3: Prompt Optimizationdef ask_llm(user_input: str) -> str:"""Optimizes a user‑provided prompt for better results in commercial LLMs by rewriting it using the Groq chat endpoint.Args:user_input (str): The original prompt to optimize.Returns:A single string containing the optimized prompt."""client = Groq(api_key=os.getenv("GROQ_API_KEY"))resp = client.chat.completions.create(model="llama-3.3-70b-versatile",messages=[{"role": "system","content": ("You are a prompt‑engineering expert. The user will give you ""simple prompts, and you should rewrite them so they get better ""results from commercial web‑based LLMs. Only return the optimized prompt.")},{"role": "user", "content": user_input},],)return resp.choices[0].message.content# --- Gradio Interface Setup ---# Sentiment Analysis interfacesentiment_interface = gr.Interface(5 unmodified linesdescription="Analyzes the sentiment of a piece of text.")# Joke Generation interfacejoke_interface = gr.Interface(fn=joke_generation,33 unmodified lines))# Prompt Optimization interfaceprompt_interface = gr.Interface(fn=ask_llm,inputs=gr.Textbox(lines=5, placeholder="Enter prompt to optimize..."),outputs=gr.Textbox(label="Optimized Prompt"),api_name="ask_llm",title="Prompt Optimization Tool",description="Rewrites user prompts to improve results from commercial LLMs.")# Combine into a tabbed demodemo = gr.TabbedInterface([joke_interface, sentiment_interface, prompt_interface],["Joke Generation", "Sentiment Analysis", "Prompt Optimization"])if __name__ == "__main__":5 unmodified lines
app.py+236-15