abdibrokhim commited on
Commit
954241d
·
1 Parent(s): 85cec0e

using gr.ChatInterface

Browse files
Files changed (1) hide show
  1. app.py +99 -95
app.py CHANGED
@@ -3,84 +3,85 @@ import requests
3
  import gradio as gr
4
  from openai import OpenAI
5
  from dotenv import load_dotenv
6
- from helpers import format_images, format_videos, format_links, format_local_map, format_knowledge
 
7
 
8
  # Load API key from .env
9
  load_dotenv()
10
  AIML_API_KEY = os.getenv('AIML_API_KEY')
11
  API_URL = 'https://api.aimlapi.com'
12
 
13
- # Bagoodex API client encapsulation
14
- class BagoodexClient:
15
- def __init__(self, api_key=AIML_API_KEY, api_url=API_URL):
16
- self.api_key = api_key
17
- self.api_url = api_url
18
- self.client = OpenAI(base_url=self.api_url, api_key=self.api_key)
19
-
20
- def complete_chat(self, query):
21
- response = self.client.chat.completions.create(
22
- model="bagoodex/bagoodex-search-v1",
23
- messages=[{"role": "user", "content": query}],
24
- )
25
- followup_id = response.id # unique ID for followup searches
26
- answer = response.choices[0].message.content
27
- return followup_id, answer
28
-
29
- def get_links(self, followup_id):
30
- headers = {"Authorization": f"Bearer {self.api_key}"}
31
- params = {"followup_id": followup_id}
32
- response = requests.get(f"{self.api_url}/v1/bagoodex/links", headers=headers, params=params)
33
- return response.json()
34
-
35
- def get_images(self, followup_id):
36
- headers = {"Authorization": f"Bearer {self.api_key}"}
37
- params = {"followup_id": followup_id}
38
- response = requests.get(f"{self.api_url}/v1/bagoodex/images", headers=headers, params=params)
39
- return response.json()
40
-
41
- def get_videos(self, followup_id):
42
- headers = {"Authorization": f"Bearer {self.api_key}"}
43
- params = {"followup_id": followup_id}
44
- response = requests.get(f"{self.api_url}/v1/bagoodex/videos", headers=headers, params=params)
45
- return response.json()
46
-
47
- def get_local_map(self, followup_id):
48
- headers = {"Authorization": f"Bearer {self.api_key}"}
49
- params = {"followup_id": followup_id}
50
- response = requests.get(f"{self.api_url}/v1/bagoodex/local-map", headers=headers, params=params)
51
- return response.json()
52
 
53
- def get_knowledge(self, followup_id):
54
- headers = {"Authorization": f"Bearer {self.api_key}"}
55
- params = {"followup_id": followup_id}
56
- response = requests.get(f"{self.api_url}/v1/bagoodex/knowledge", headers=headers, params=params)
57
- return response.json()
 
 
 
 
 
 
 
 
 
 
 
58
 
59
- client = BagoodexClient()
 
 
60
 
61
- # Callback functions
62
- def chat_response(user_input, chat_history, followup_id):
63
- followup_id_new, answer = client.complete_chat(user_input)
64
- chat_history = chat_history or []
65
- chat_history.append((user_input, answer))
66
- return "", chat_history, followup_id_new
67
 
68
- def perform_local_map_search(followup_id, chat_history):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  if not followup_id:
70
- return chat_history
71
  result = client.get_local_map(followup_id)
72
  formatted = format_local_map(result)
73
- chat_history.append((None, formatted))
74
- return chat_history
75
 
76
- def perform_knowledge_search(followup_id, chat_history):
77
  if not followup_id:
78
- return chat_history
79
  result = client.get_knowledge(followup_id)
80
  formatted = format_knowledge(result)
81
- chat_history.append((None, formatted))
82
- return chat_history
83
 
 
84
  def perform_image_search(followup_id):
85
  if not followup_id:
86
  return []
@@ -88,19 +89,13 @@ def perform_image_search(followup_id):
88
  urls = format_images(result)
89
  return urls
90
 
91
- def perform_video_search(followup_id):
92
- if not followup_id:
93
- return "No followup ID available."
94
- result = client.get_videos(followup_id)
95
- return format_videos(result)
96
-
97
  def perform_links_search(followup_id):
98
  if not followup_id:
99
- return "No followup ID available."
100
  result = client.get_links(followup_id)
101
  return format_links(result)
102
 
103
- # Custom CSS to help the chat component fill the available height
104
  css = """
105
  #chatbot {
106
  height: 100%;
@@ -109,32 +104,29 @@ css = """
109
 
110
  # Build UI
111
  with gr.Blocks(css=css, fill_height=True) as demo:
 
112
  with gr.Row():
113
- # Left column: Chat interface
114
  with gr.Column(scale=3):
115
- chatbot = gr.Chatbot(label="Bagoodex Chat", elem_id="chatbot")
116
- # State variables: chat history and followup ID.
117
- chat_history_state = gr.State([])
118
- followup_state = gr.State(None)
119
- # Two small buttons placed above the input field:
120
  with gr.Row():
121
  btn_local_map = gr.Button("Local Map Search", variant="secondary", size="sm")
122
  btn_knowledge = gr.Button("Knowledge Base", variant="secondary", size="sm")
123
- # Chat input area: textbox and explicit submit button.
124
- with gr.Row():
125
- txt = gr.Textbox(placeholder="Enter your query here...", show_label=False, scale=7)
126
- submit_btn = gr.Button("Submit", scale=1)
127
- # Wire up the chat callbacks:
128
- submit_btn.click(chat_response, inputs=[txt, chat_history_state, followup_state],
129
- outputs=[txt, chatbot, followup_state])
130
- txt.submit(chat_response, inputs=[txt, chat_history_state, followup_state],
131
- outputs=[txt, chatbot, followup_state])
132
- # The two additional search buttons update the chat history by appending a new assistant message.
133
- btn_local_map.click(perform_local_map_search, inputs=[followup_state, chat_history_state],
134
- outputs=[chatbot, chat_history_state])
135
- btn_knowledge.click(perform_knowledge_search, inputs=[followup_state, chat_history_state],
136
- outputs=[chatbot, chat_history_state])
137
- # Right column: Advanced search options for images, videos, and links.
 
 
138
  with gr.Column(scale=1):
139
  gr.Markdown("### Advanced Search Options")
140
  with gr.Column(variant="panel"):
@@ -142,9 +134,21 @@ with gr.Blocks(css=css, fill_height=True) as demo:
142
  btn_videos = gr.Button("Search Videos")
143
  btn_links = gr.Button("Search Links")
144
  gallery_output = gr.Gallery(label="Image Results", columns=2)
145
- video_output = gr.HTML(label="Video Results")
146
- links_output = gr.HTML(label="Links Results")
147
- btn_images.click(perform_image_search, inputs=[followup_state], outputs=[gallery_output])
148
- btn_videos.click(perform_video_search, inputs=[followup_state], outputs=[video_output])
149
- btn_links.click(perform_links_search, inputs=[followup_state], outputs=[links_output])
150
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import gradio as gr
4
  from openai import OpenAI
5
  from dotenv import load_dotenv
6
+ # from helpers import format_images, format_videos, format_links, format_local_map, format_knowledge
7
+ from bagoodex_client import BagoodexClient
8
 
9
  # Load API key from .env
10
  load_dotenv()
11
  AIML_API_KEY = os.getenv('AIML_API_KEY')
12
  API_URL = 'https://api.aimlapi.com'
13
 
14
+ client = BagoodexClient()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ def format_knowledge(result):
17
+ title = result.get('title', 'Unknown')
18
+ type_ = result.get('type', '')
19
+ born = result.get('born', '')
20
+ died = result.get('died', '')
21
+ content = f"""
22
+ **{title}**
23
+ Type: {type_}
24
+ Born: {born}
25
+ Died: {died}
26
+ """
27
+ return gr.Markdown(content)
28
+
29
+ def format_images(result):
30
+ urls = [item.get("original", "") for item in result]
31
+ return urls
32
 
33
+ # Helper formatting functions
34
+ def format_videos(result):
35
+ return [vid.get('link', '') for vid in result]
36
 
37
+ # Advanced search functions
38
+ def perform_video_search(followup_id):
39
+ if not followup_id:
40
+ return []
41
+ result = client.get_videos(followup_id)
42
+ return format_videos(result)
43
 
44
+ def format_links(result):
45
+ links_md = "**Links:**\n"
46
+ for url in result:
47
+ title = url.rstrip('/').split('/')[-1]
48
+ links_md += f"- [{title}]({url})\n"
49
+ return gr.Markdown(links_md)
50
+
51
+ # Define the chat function
52
+ def chat_function(message, history, followup_id):
53
+ followup_id_new, answer = client.complete_chat(message)
54
+ return answer, followup_id_new
55
+
56
+ def format_local_map(result):
57
+ link = result.get('link', '')
58
+ image_url = result.get('image', '')
59
+ html = f"""
60
+ <div>
61
+ <strong>Local Map:</strong><br>
62
+ <a href='{link}' target='_blank'>View on Google Maps</a><br>
63
+ <img src='{image_url}' style='width:100%;'/>
64
+ </div>
65
+ """
66
+ return gr.HTML(html)
67
+
68
+ def append_local_map(followup_id, chatbot_value):
69
  if not followup_id:
70
+ return chatbot_value
71
  result = client.get_local_map(followup_id)
72
  formatted = format_local_map(result)
73
+ new_message = {"role": "assistant", "content": formatted}
74
+ return chatbot_value + [new_message]
75
 
76
+ def append_knowledge(followup_id, chatbot_value):
77
  if not followup_id:
78
+ return chatbot_value
79
  result = client.get_knowledge(followup_id)
80
  formatted = format_knowledge(result)
81
+ new_message = {"role": "assistant", "content": formatted}
82
+ return chatbot_value + [new_message]
83
 
84
+ # Define advanced search functions
85
  def perform_image_search(followup_id):
86
  if not followup_id:
87
  return []
 
89
  urls = format_images(result)
90
  return urls
91
 
 
 
 
 
 
 
92
  def perform_links_search(followup_id):
93
  if not followup_id:
94
+ return gr.Markdown("No followup ID available.")
95
  result = client.get_links(followup_id)
96
  return format_links(result)
97
 
98
+ # Custom CSS
99
  css = """
100
  #chatbot {
101
  height: 100%;
 
104
 
105
  # Build UI
106
  with gr.Blocks(css=css, fill_height=True) as demo:
107
+ followup_state = gr.State(None)
108
  with gr.Row():
 
109
  with gr.Column(scale=3):
 
 
 
 
 
110
  with gr.Row():
111
  btn_local_map = gr.Button("Local Map Search", variant="secondary", size="sm")
112
  btn_knowledge = gr.Button("Knowledge Base", variant="secondary", size="sm")
113
+ chat = gr.ChatInterface(
114
+ fn=chat_function,
115
+ type="messages",
116
+ additional_inputs=[followup_state],
117
+ additional_outputs=[followup_state],
118
+ )
119
+ # Wire up the buttons to append to chat history
120
+ btn_local_map.click(
121
+ append_local_map,
122
+ inputs=[followup_state, chat.chatbot],
123
+ outputs=chat.chatbot
124
+ )
125
+ btn_knowledge.click(
126
+ append_knowledge,
127
+ inputs=[followup_state, chat.chatbot],
128
+ outputs=chat.chatbot
129
+ )
130
  with gr.Column(scale=1):
131
  gr.Markdown("### Advanced Search Options")
132
  with gr.Column(variant="panel"):
 
134
  btn_videos = gr.Button("Search Videos")
135
  btn_links = gr.Button("Search Links")
136
  gallery_output = gr.Gallery(label="Image Results", columns=2)
137
+ video_output = gr.Gallery(label="Video Results", columns=1, visible=True)
138
+ links_output = gr.Markdown(label="Links Results")
139
+ btn_images.click(
140
+ perform_image_search,
141
+ inputs=[followup_state],
142
+ outputs=[gallery_output]
143
+ )
144
+ btn_videos.click(
145
+ perform_video_search,
146
+ inputs=[followup_state],
147
+ outputs=[video_output]
148
+ )
149
+ btn_links.click(
150
+ perform_links_search,
151
+ inputs=[followup_state],
152
+ outputs=[links_output]
153
+ )
154
+ demo.launch()