-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
393 lines (269 loc) · 10.2 KB
/
main.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
#import uvicorn
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
import pyreadstat
import time
from typing import List
from src.DataUtils import DataUtils
from src.DataDictionary import DataDictionary
from src.DataDictionaryCsv import DataDictionaryCsv
from src.ExportDatafile import ExportDatafile
import re
import pandas as pd
import numpy as np
import os
from pydantic import BaseSettings
import json
from src.DictParams import DictParams
import asyncio
import functools
import hashlib
import datetime
from fastapi.concurrency import run_in_threadpool
import shutil
import glob
from fastapi.exception_handlers import (
http_exception_handler,
request_validation_exception_handler,
)
from starlette.exceptions import HTTPException as StarletteHTTPException
class Settings(BaseSettings):
storage_path: str = "data"
settings = Settings()
class FileInfo(BaseModel):
file_path: str
class WeightsColumns(BaseModel):
weight_field: str
field: str
class UserMissings(BaseModel):
field: str
missings: List[str]
class VarInfo(BaseModel):
file_path: str
var_names: List[str]
weights: List[WeightsColumns] = []
missings: List[UserMissings] = []
datadict=DataDictionary()
app = FastAPI()
app.fifo_queue = asyncio.Queue()
app.jobs = {}
@app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request, exc):
import traceback
print(traceback.format_exc())
print(f"error: {repr(exc)}")
return await http_exception_handler(request, exc)
@app.get("/")
async def root(request: Request):
return {"message": "PyDataTool API - See documentation at " + str(request.url) + "docs"}
@app.get("/status")
async def status():
return {"status": "ok"}
@app.post("/metadata")
async def metadata(fileinfo: FileInfo):
datadict=DataDictionary()
return datadict.get_metadata(fileinfo)
@app.post("/name-labels")
async def name_labels(fileinfo: FileInfo):
datadict=DataDictionary()
return datadict.get_name_labels(fileinfo)
@app.post("/data-dictionary")
async def data_dictionary(fileinfo: FileInfo):
datadict=DataDictionary()
return datadict.get_data_dictionary(fileinfo)
@app.post("/data-dictionary-variable")
async def data_dictionary_variable(params: DictParams):
file_ext=os.path.splitext(params.file_path)[1]
if file_ext.lower() == '.csv':
datadict=DataDictionaryCsv()
else:
datadict=DataDictionary()
return datadict.get_data_dictionary_variable(params)
@app.post("/generate-csv")
async def write_csv(fileinfo: FileInfo):
return write_csv_file(fileinfo)
def write_csv_file(fileinfo: FileInfo):
file_ext=os.path.splitext(fileinfo.file_path)[1]
folder_path=os.path.dirname(fileinfo.file_path)
file_exists=os.path.exists(fileinfo.file_path)
#if not file_exists:
# raise HTTPException(status_code=400, detail="file not found: " + fileinfo.file_path)
try:
if file_ext.lower() == '.dta':
try:
df,meta = pyreadstat.read_dta(fileinfo.file_path)
except UnicodeDecodeError as e:
df,meta = pyreadstat.read_dta(fileinfo.file_path, encoding="latin1")
elif file_ext == '.sav':
df, meta = pyreadstat.read_sav(fileinfo.file_path)
else:
return {"error": "file not supported" + file_ext}
df=df.convert_dtypes()
csv_filepath = os.path.join(folder_path,os.path.splitext(os.path.basename(fileinfo.file_path))[0] + '.csv')
df.to_csv(csv_filepath, index=False)
except Exception as e:
#print("error-writing-csv================= " + str(e))
raise HTTPException(status_code=400, detail="error writing csv file: " + str(e))
output = {
#'path':os.path.abspath(os.getcwd()),
#'abspath':os.path.dirname(os.path.abspath(__file__)),
#'filename':os.path.basename(fileinfo.file_path),
#'file_ext':os.path.splitext(fileinfo.file_path)[1],
#'file_path':os.path.dirname(fileinfo.file_path),
#'file_exists':os.path.exists(fileinfo.file_path),
'status':'success',
'csv_file':csv_filepath,
'csv_file_size': DataUtils.sizeof_fmt(os.path.getsize(csv_filepath))
}
return output
def detect_column_types(df,meta):
if meta.number_rows > 20000:
df_sample=df.sample(n=5000, random_state=1)
df_types=df_sample.convert_dtypes()
else:
df_types=df.convert_dtypes()
return df_types.dtypes.to_dict()
async def fifo_worker():
print("Starting FIFO worker")
# remove old jobs
remove_jobs_folder()
while True:
job = await app.fifo_queue.get()
print(f"Got a job: (size of remaining queue: {app.fifo_queue.qsize()})")
await job()
@app.on_event("startup")
async def start_queue():
asyncio.create_task(fifo_worker())
@app.post("/data-dictionary-queue")
async def data_dictionary_queue(params: DictParams):
jobid='job-' + str(time.time())
app.jobs[jobid]={
"jobid":jobid,
"jobtype":"data-dictionary",
"status":"queued",
"info":params
}
data_dict_callback = functools.partial(write_data_dictionary_file, jobid, params)
await app.fifo_queue.put( data_dict_callback )
return JSONResponse(status_code=202, content={
"message": "Item is queued",
"job_id": jobid
})
@app.post("/generate-csv-queue")
async def write_csv_queue(fileinfo: FileInfo):
jobid='job-' + str(time.time())
app.jobs[jobid]={
"jobid":jobid,
"jobtype":"generate-csv",
"status":"queued",
"info":fileinfo
}
generate_csv_callback=functools.partial(write_csv_file_callback, jobid, fileinfo)
await app.fifo_queue.put( generate_csv_callback )
return JSONResponse(status_code=202, content={
"message": "file is queued",
"job_id": jobid
})
async def write_csv_file_callback(jobid, fileinfo: FileInfo):
loop = asyncio.get_running_loop()
app.jobs[jobid]["status"]="processing"
try:
result=await loop.run_in_executor(None, write_csv_file, fileinfo)
except Exception as e:
print ("exception writing csv file", e)
app.jobs[jobid]["status"]="error"
app.jobs[jobid]["error"]="failed to write csv file: " + str(e)
return {"status":"failed"}
app.jobs[jobid]["status"]="done"
file_path=os.path.join('jobs', str(jobid) + '.json')
with open(file_path, 'w') as outfile:
json.dump(result, outfile)
return {"status": "success", "file_path": file_path}
async def write_data_dictionary_file(jobid, params: DictParams):
loop = asyncio.get_running_loop()
file_ext=os.path.splitext(params.file_path)[1]
if file_ext.lower() == '.csv':
datadict=DataDictionaryCsv()
else:
datadict=DataDictionary()
app.jobs[jobid]["status"]="processing"
try:
result=await loop.run_in_executor(None, datadict.get_data_dictionary_variable, params)
app.jobs[jobid]["status"]="done"
file_path=os.path.join('jobs', str(jobid) + '.json')
with open(file_path, 'w') as outfile:
json.dump(result, outfile)
return {"status": "success", "file_path": file_path}
except Exception as e:
import traceback
app.jobs[jobid]["status"]="error"
app.jobs[jobid]["error"]=str(e)
app.jobs[jobid]["traceback"]=traceback.format_exc()
return {"status": "error", "error": str(e)}
@app.post("/export-data-queue")
async def export_data_queue(params: DictParams):
print ("export_data_queue", params)
jobid='job-' + str(time.time())
app.jobs[jobid]={
"jobid":jobid,
"jobtype":"data-export",
"status":"queued",
"info":params
}
data_export_callback = functools.partial(export_data_file, jobid, params)
await app.fifo_queue.put( data_export_callback )
return JSONResponse(status_code=202, content={
"message": "Item is queued",
"job_id": jobid
})
async def export_data_file(jobid, params: DictParams):
loop = asyncio.get_running_loop()
file_ext=os.path.splitext(params.file_path)[1]
exportDF=ExportDatafile()
app.jobs[jobid]["status"]="processing"
try:
result=await loop.run_in_executor(None, exportDF.export_file, params)
app.jobs[jobid]["status"]="done"
file_path=os.path.join('jobs', str(jobid) + '.json')
with open(file_path, 'w') as outfile:
json.dump(result, outfile)
return {"status": "success", "file_path": file_path}
except Exception as e:
app.jobs[jobid]["status"]="error"
app.jobs[jobid]["error"]=str(e)
return {"status": "error", "error": str(e)}
@app.get("/jobs")
async def queue_items():
return {
"queue_size": app.fifo_queue.qsize(),
"active_jobs": app.jobs
}
@app.get("/jobs/{jobid}")
async def queue_items(jobid: str):
if jobid in app.jobs:
job=app.jobs[jobid]
if (job["status"]=="done"):
data={}
file_path=os.path.join('jobs', str(jobid) + '.json')
if os.path.exists(file_path):
with open(file_path) as json_file:
data = json.load(json_file)
else:
raise HTTPException(status_code=400, detail="Failed to load job data")
job_response=job.copy()
job_response['data']=data
return job_response
elif (job["status"]=="error"):
raise HTTPException(status_code=400, detail=job['error'])
else:
return job
raise HTTPException(status_code=404, detail="Job not found")
def remove_jobs_folder():
folder_path=os.path.join(os.getcwd(), 'jobs')
if os.path.exists(folder_path):
files = glob.glob(folder_path + '/*.json')
for f in files:
os.remove(f)
#if __name__ == "__main__":
# uvicorn.run(app, host="0.0.0.0", port=8000)