Spaces:
Running
Running
# x.com/xyizko | |
import gradio as gr | |
import asyncio | |
from jokeapi import Jokes | |
def jokerz(): | |
"""Main function containing all sub-functions for fetching and displaying jokes.""" | |
async def get_joke(): | |
"""Fetch a random joke asynchronously from JokeAPI.""" | |
j = await Jokes() | |
joke = await j.get_joke() | |
if isinstance(joke, list): | |
joke = joke[0] | |
return ( | |
joke["joke"] | |
if joke["type"] == "single" | |
else f"{joke['setup']} - {joke['delivery']}" | |
) | |
def fetch_joke(): | |
"""Handles sync & async cases without crashing.""" | |
try: | |
return asyncio.run(get_joke()) | |
except RuntimeError: | |
loop = asyncio.get_event_loop() | |
return loop.run_until_complete(get_joke()) | |
def get_joke_response(message, history): | |
"""Handles incoming chat messages and returns a joke.""" | |
return fetch_joke() | |
def run_interface(): | |
"""Creates and returns the Gradio ChatInterface.""" | |
return gr.ChatInterface( | |
get_joke_response, | |
type="messages", | |
title=" xyizko - Random Joke Generator 🤣", | |
description="Get random jokes from JokeAPI!", | |
) | |
jokeapp = run_interface() | |
jokeapp.launch() | |
if __name__ == "__main__": | |
jokerz() |