xyizko commited on
Commit
0569a5d
·
verified ·
1 Parent(s): 8e59e89

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -0
app.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import asyncio
3
+ from jokeapi import Jokes
4
+
5
+
6
+ def main():
7
+ jokerz()
8
+
9
+ def jokerz():
10
+ """Main function containing all sub-functions for fetching and displaying jokes."""
11
+
12
+ async def get_joke():
13
+ """Fetch a random joke asynchronously from JokeAPI."""
14
+ j = Jokes()
15
+ joke = j.get_joke()
16
+
17
+ if isinstance(joke, list):
18
+ joke = joke[0]
19
+
20
+ return (
21
+ joke["joke"]
22
+ if joke["type"] == "single"
23
+ else f"{joke['setup']} - {joke['delivery']}"
24
+ )
25
+
26
+ def fetch_joke():
27
+ """Handles sync & async cases without crashing."""
28
+ try:
29
+ return asyncio.run(get_joke())
30
+ except RuntimeError:
31
+ loop = asyncio.get_event_loop()
32
+ return loop.run_until_complete(get_joke())
33
+
34
+ def get_joke_response(message, history):
35
+ """Handles incoming chat messages and returns a joke."""
36
+ return fetch_joke()
37
+
38
+ def run_interface():
39
+ """Creates and returns the Gradio ChatInterface."""
40
+ return gr.ChatInterface(
41
+ get_joke_response,
42
+ type="messages",
43
+ title="Chat with a Random Joke Generator 🤣",
44
+ description="Chat and get random jokes from JokeAPI!",
45
+ )
46
+
47
+
48
+ demo = run_interface()
49
+ demo.launch()
50
+
51
+ if __name__ == "__main__":
52
+ main()