Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from fastapi import FastAPI, Request, HTTPException
|
3 |
+
from concurrent.futures import ProcessPoolExecutor
|
4 |
+
from typing import List, Optional
|
5 |
+
from commonmeta import Metadata
|
6 |
+
from pydantic import BaseModel
|
7 |
+
|
8 |
+
app = FastAPI()
|
9 |
+
|
10 |
+
executor = ProcessPoolExecutor(max_workers=os.cpu_count())
|
11 |
+
|
12 |
+
def parse(string: str, via: str = None, to: str = None, **kwargs):
|
13 |
+
try:
|
14 |
+
metadata = Metadata(string=string, via=via, **kwargs)
|
15 |
+
if not metadata.is_valid:
|
16 |
+
raise ValueError(f"Error in parsing metadata, please verify the format.")
|
17 |
+
except Exception as e:
|
18 |
+
raise ValueError(f"Metadata fetch error: {str(e)}")
|
19 |
+
|
20 |
+
try:
|
21 |
+
parsed_metadata = metadata.write(to=to)
|
22 |
+
return parsed_metadata
|
23 |
+
except Exception as e:
|
24 |
+
raise ValueError(f"Metadata write error: {str(e)}")
|
25 |
+
|
26 |
+
def process_single(args):
|
27 |
+
string, via, to, kwargs = args
|
28 |
+
try:
|
29 |
+
return parse(string, via=via, to=to, **kwargs)
|
30 |
+
except ValueError as e:
|
31 |
+
return {"error": str(e), "string": string}
|
32 |
+
|
33 |
+
@app.get("/parse")
|
34 |
+
async def parse_one(request: Request, string: str, to: str = None, via: str = None):
|
35 |
+
kwargs = dict(request.query_params)
|
36 |
+
kwargs.pop('string', None)
|
37 |
+
kwargs.pop('to', None)
|
38 |
+
kwargs.pop('via', None)
|
39 |
+
|
40 |
+
try:
|
41 |
+
parsed_metadata = parse(string, via=via, to=to, **kwargs)
|
42 |
+
return {'data': parsed_metadata}
|
43 |
+
except ValueError as e:
|
44 |
+
raise HTTPException(status_code=400, detail=str(e))
|
45 |
+
|
46 |
+
class BatchParseRequest(BaseModel):
|
47 |
+
strings: str = ""
|
48 |
+
to: str = None
|
49 |
+
via: str = None
|
50 |
+
|
51 |
+
@app.post("/parse_batch")
|
52 |
+
async def batch_parse(payload: BatchParseRequest):
|
53 |
+
kwargs = payload.dict()
|
54 |
+
strings = kwargs.pop("strings").split(",")
|
55 |
+
to = kwargs.pop("to", None)
|
56 |
+
via = kwargs.pop("via", None)
|
57 |
+
|
58 |
+
task_args = [(s, via, to, kwargs) for s in strings]
|
59 |
+
|
60 |
+
results = list(executor.map(process_single, task_args))
|
61 |
+
|
62 |
+
return {"batch": results}
|