-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
400 lines (333 loc) · 9.54 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import uuid
from enum import Enum
from functools import reduce
from operator import add
from typing import Annotated, Any, Dict, List, Optional, Set
import commons
import config
import constants
from api_clients.wrappers import DeezerWrapper
from commons import str_to_values
from fastapi import FastAPI, Header
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.responses import JSONResponse
from items import ItemStore
from status import StatusManager
from tasks import TaskManager
class Tags(Enum):
SESSION = "Session"
CACHE = "Cache"
ITEMS = "Items"
TASKS = "Tasks"
INTERACTIONS = "Interactions"
TECHNICAL = "Technical"
dzg_api = FastAPI(
title="Deezer Graph API",
default_response_class=JSONResponse,
)
origins = [
"http://localhost:8080",
"http://192.168.1.155:8080",
"http://localhost:8502",
"https://tdambrin.github.io",
# "*",
]
dzg_api.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=[
"GET",
],
allow_headers=["*"],
)
if config.APITALLY_CLIENT_ID is not None:
from apitally.fastapi import ApitallyMiddleware, RequestLoggingConfig
dzg_api.add_middleware(
ApitallyMiddleware,
client_id=config.APITALLY_CLIENT_ID,
env="prod",
request_logging_config=RequestLoggingConfig(
enabled=True,
log_query_params=True,
log_request_body=True,
),
)
# --- Sessions ---
@dzg_api.get("/api/sessions/create", tags=[Tags.SESSION])
def get_session_params() -> Dict[str, str]:
"""
Get new session id
Returns:
(str) uuid
"""
return {"session_id": str(uuid.uuid4())}
@dzg_api.get("/api/sessions/restore", tags=[Tags.SESSION])
def restore_session(
session_id: Annotated[str, Header()],
) -> Dict[str, Any]:
"""
Restore session
Args:
session_id (str): uuid
Returns:
{
"graph_keys": List[str],
"nodes": List[Dict[str, Any]],
"edges": List[Dict[str, Any]]
}
"""
graphs = ItemStore().get_graphs(session_id=session_id)
if not graphs:
return {}
return {
"graph_keys": list(graphs.keys()),
"nodes": reduce(
add,
[
commons.nodes_edges_to_list_of_dict(
graph_, which=constants.NODES
)
for graph_ in graphs.values()
],
),
"edges": reduce(
add,
[
commons.nodes_edges_to_list_of_dict(
graph_, which=constants.EDGES, system_=constants.VIS_JS_SYS
)
for graph_ in graphs.values()
],
),
}
# --- Graph Interactions ---
@dzg_api.get("/api/search/{keywords}", tags=[Tags.INTERACTIONS])
def search(
keywords: str,
selected_types: str,
session_id: Annotated[str, Header()],
) -> Dict[str, Any]:
"""
Start new search. Will override graphs with same keywords in same session.
Args:
keywords (str): '+' separated
selected_types (str): '+' separated
session_id (str): uuid
Returns:
{
"task_id": uuid,
"nodes": List[Dict[str, Any]],
"edges": List[Dict[str, Any]]
}
"""
# Parse params
keywords_: List[str] = commons.str_to_values(keywords, sep="+")
selected_types_: List[str] = commons.str_to_values(selected_types, sep="+")
# Start search
ctrl = TaskManager(session_id=session_id, selected_types=selected_types_)
return ctrl.search_task(keywords=keywords_, save=False)
@dzg_api.get("/api/expand/{graph_key}/{node_id}", tags=[Tags.INTERACTIONS])
def start_expand(
graph_key: str,
node_id: int,
selected_types: str,
session_id: Annotated[str, Header()],
item_type: Optional[str] = None,
) -> Dict[str, Any]:
"""
Expand graph from node.
Args:
graph_key (str): identifier of query node
node_id (int): seed node id
selected_types (str): subset of ['album', 'artist','track'], '+' sep
session_id (str): uuid
item_type: one of ['album', 'artist','track']
Returns:
{
"task_id": uuid
}
"""
ctrl = TaskManager(
session_id=session_id,
graph_key=graph_key,
selected_types=str_to_values(selected_types, sep="+"),
)
task_id = ctrl.start_expand_task(
node_id=node_id, item_type=item_type, save=False
)
return {"task_id": task_id}
@dzg_api.get("/api/delete/{graph_key}/{node_id}", tags=[Tags.INTERACTIONS])
def delete(
graph_key: str,
node_id: int,
session_id: Annotated[str, Header()],
cascading: bool = True,
) -> Dict[str, Any]:
"""
Delete node from graph.
Args:
graph_key (str): identifier of query node
node_id (int): seed node id
session_id (str): uuid
cascading (bool): whether successors are deleted too
Returns:
Deleted nodes.
{
"nodes": List[Dict[str, Any]]
}
"""
nodes_to_delete = {node_id}
if cascading:
nodes_to_delete = nodes_to_delete.union(
ItemStore().get_successors(
session_id=session_id,
graph_key=graph_key,
node_id=node_id,
recursive=True,
)
)
ItemStore().delete_nodes(
session_id=session_id,
graph_key=graph_key,
nodes_ids=list(nodes_to_delete),
)
return {
"nodes": nodes_to_delete,
}
# --- Tasks ---
@dzg_api.get("/api/tasks/{task_id}/status", tags=[Tags.TASKS])
def get_task_status(task_id: str) -> Dict[str, Any]:
"""
Get task status.
Args:
task_id (str): uuid
Returns:
{
"status": one of (idle, running, created, failed, completed, not_found),
"error": str if any,
**task_result if task result is dict else "result": single result
}
""" # noqa: E501
return StatusManager().get_status_and_result(task_id=task_id)
@dzg_api.get("/api/tasks", tags=[Tags.TASKS])
def get_all_tasks() -> List[Dict[str, Any]]:
"""
Get all tasks and their status
Returns:
[{
"status": one of (idle, running, created, failed, completed, not_found),
"error": str if any,
"result": task result
}]
""" # noqa: E501
return StatusManager().all_tasks
@dzg_api.get("/api/cache/items", tags=[Tags.CACHE])
def get_cached_items() -> Dict[str, Dict[int, Any]]:
"""
Get all items in store
Returns:
{
"items": [{item}]
}
"""
all_items = ItemStore().get_all_items()
return {
"items": {item_.id: item_.as_dict() for item_ in all_items.values()}
}
@dzg_api.get("/api/cache/items/{item_id}", tags=[Tags.CACHE])
def get_cached_item(item_id: int) -> Dict[str, Any]:
"""
Get item in store
Args:
item_id (str): deezer id
Returns:
{
"item": {item}
}
"""
return {"item": ItemStore().get(item_id)}
@dzg_api.get("/api/items/{item_id}/successors", tags=[Tags.ITEMS])
def get_item_successors(
item_id: int,
graph_key: str,
session_id: Annotated[str, Header()],
recursive: bool = True,
) -> Set[int]:
"""
Get item successor in a session graph
Args:
graph_key (str): identifier of query node
item_id (int): seed node id
session_id (str): uuid
recursive (bool): whether to get successors' successors
Returns:
list of node ids
"""
return ItemStore().get_successors(
session_id=session_id,
graph_key=graph_key,
node_id=item_id,
recursive=recursive,
)
@dzg_api.get("/api/items/{item_id}/predecessors", tags=[Tags.ITEMS])
def get_item_predecessors(
item_id: int,
graph_key: str,
session_id: Annotated[str, Header()],
recursive: bool = True,
) -> Set[int]:
"""
Get item predecessors in a session graph
Args:
graph_key (str): identifier of query node
item_id (int): seed node id
session_id (str): uuid
recursive (bool): whether to get predecessors' predecessors
Returns:
list of node ids
"""
return ItemStore().get_predecessors(
session_id=session_id,
graph_key=graph_key,
node_id=item_id,
recursive=recursive,
)
@dzg_api.get("/api/items/{item_id}", tags=[Tags.ITEMS])
def get_item_from_deezer(item_id: int, item_type: str) -> Dict[str, Any]:
"""
Get item in store
Args:
item_id (int): deezer id
item_type (str): one of ['album', 'artist','track']
Returns:
{
"item": {item}
}
"""
return {
"item": DeezerWrapper()
.find(item_id=item_id, item_type=item_type)
.as_dict()
}
@dzg_api.get("/docs", include_in_schema=False, tags=[Tags.TECHNICAL])
async def get_documentation():
return get_swagger_ui_html(openapi_url="/openapi.json", title="docs")
@dzg_api.get("/health", include_in_schema=False, tags=[Tags.TECHNICAL])
async def health():
return {"state": "up"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(dzg_api, host="127.0.0.1", port=8502, log_level="info")
# Thread version - not reached
import threading
threading.Thread(
target=uvicorn.run,
kwargs={
"app": dzg_api,
"host": config.API_HOST,
"port": config.API_PORT,
"log_level": "info",
},
).start()