-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
150 lines (123 loc) · 3.78 KB
/
main.py
File metadata and controls
150 lines (123 loc) · 3.78 KB
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
from typing import List
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from predictor import pred_model, predict
from models import (
BatchPaperPredictions,
ErrorResponse,
HealthCheckResponse,
PaperInput,
SinglePaperPrediction,
)
app = FastAPI()
@app.get("/")
@app.get("/health_check", response_model=HealthCheckResponse)
async def health_check():
"""Check if the service and model are healthy and operational.
Returns
-------
JSONResponse
with service health status and details
Raises
------
HTTPException
If model or service is unhealthy
"""
try:
if not pred_model:
raise HTTPException(status_code=503, detail="Model not initialized")
_ = pred_model.get_layer("output_layer")
return JSONResponse(
content={
"status": "healthy",
"model": "loaded",
}
)
except HTTPException as he:
raise he
except Exception as e:
raise HTTPException(status_code=503, detail=f"Service unhealthy: {str(e)}")
@app.post(
"/single",
response_model=SinglePaperPrediction,
responses={400: {"model": ErrorResponse}, 500: {"model": ErrorResponse}},
)
async def single(paper_input: List[PaperInput]):
"""Process academic papers and return topic predictions.
Takes a list of papers with their metadata and returns topic predictions:
- Validates input JSON format
- Processes titles and abstracts
- Analyses citations
- Returns topic IDs, labels and confidence scores for each paper
Parameters
----------
paper_input : List[PaperInput]
A list containing a single paper's metadata.
Returns
-------
JSONResponse
with a list of predictions for the paper.
For example:
[
[
{
"topic_id": int,
"topic_label": str,
"topic_score": float
},
...
],
...
]
Raises
------
HTTPException
If invalid JSON or processing error occurs
"""
try:
if len(paper_input) > 1:
return JSONResponse(
status_code=400,
content={"Error": "Only one paper can be processed at a time"},
)
all_tags = predict([paper_input[0].dict()])
return JSONResponse(content=all_tags)
except Exception as e:
print(f"Error processing request: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/batch", response_model=BatchPaperPredictions)
async def batch(paper_inputs: List[PaperInput]):
"""Process a batch of academic papers and return topic predictions.
Parameters
----------
paper_inputs : List[PaperInput]
A list of papers with their metadata.
Returns
-------
JSONResponse
with predictions for each paper
Raises
------
HTTPException
If invalid input or processing error occurs
"""
try:
if len(paper_inputs) > 1000:
raise HTTPException(
status_code=400, detail="Batch size exceeds limit of 1000 papers"
)
if not paper_inputs:
return JSONResponse(content=[])
try:
predictions = predict([paper.dict() for paper in paper_inputs])
return JSONResponse(content=predictions)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error processing papers: {str(e)}"
)
except HTTPException as he:
raise he
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error processing batch request: {str(e)}"
)