Spaces:
Sleeping
Sleeping
Toan2004-ai commited on
Commit ·
b65cd1e
1
Parent(s): a712270
add readme config
Browse files
main.py
CHANGED
|
@@ -1,31 +1,78 @@
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
-
from pydantic import BaseModel
|
| 3 |
-
from typing import List, Optional
|
| 4 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 5 |
-
from json_repair import repair_json
|
| 6 |
-
from schema import EnergyTargetSchema
|
| 7 |
from engine import final_process_eme_technical_guided
|
| 8 |
from contextlib import asynccontextmanager
|
| 9 |
-
|
| 10 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
# Tối ưu hóa số luồng xử lý trên CPU của Cloud Run
|
| 13 |
-
torch.set_num_threads(4)
|
| 14 |
|
| 15 |
@asynccontextmanager
|
| 16 |
async def lifespan(app: FastAPI):
|
| 17 |
-
|
| 18 |
-
logger = logging.getLogger(__name__)
|
| 19 |
-
logger.info("--- [LIFESPAN] Starting to load the model into RAM... ---")
|
| 20 |
-
get_model_and_tokenizer()
|
| 21 |
yield
|
| 22 |
-
|
| 23 |
-
logger.info("--- [LIFESPAN] Stop server. ---")
|
| 24 |
|
| 25 |
-
# Cập nhật khi khai báo app
|
| 26 |
app = FastAPI(title="Volta Energy Plan Parser API", lifespan=lifespan)
|
| 27 |
|
| 28 |
-
|
| 29 |
class PredictRequest(BaseModel):
|
| 30 |
instances: list
|
| 31 |
|
|
@@ -33,19 +80,33 @@ class PredictRequest(BaseModel):
|
|
| 33 |
@app.post("/extract")
|
| 34 |
def predict(request: PredictRequest):
|
| 35 |
results = []
|
|
|
|
|
|
|
| 36 |
for instance in request.instances:
|
| 37 |
text = instance if isinstance(instance, str) else instance.get("raw_text", "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
try:
|
| 39 |
res = final_process_eme_technical_guided(text)
|
| 40 |
-
results.append(res.model_dump())
|
| 41 |
except Exception as e:
|
|
|
|
| 42 |
results.append({"error": str(e)})
|
|
|
|
| 43 |
return {"predictions": results}
|
| 44 |
|
| 45 |
@app.get("/health")
|
| 46 |
async def health():
|
| 47 |
return {"status": "healthy"}
|
| 48 |
|
| 49 |
-
|
| 50 |
-
import uvicorn
|
| 51 |
-
uvicorn.run(app, host="0.0.0.0", port=8080)
|
|
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
+
from pydantic import BaseModel
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from engine import final_process_eme_technical_guided
|
| 4 |
from contextlib import asynccontextmanager
|
| 5 |
+
import logging
|
| 6 |
+
import json
|
| 7 |
+
import gradio as gr
|
| 8 |
+
|
| 9 |
+
logging.basicConfig(level=logging.INFO)
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
def parse_energy_plan_ui(text_input):
|
| 13 |
+
if not text_input or not text_input.strip():
|
| 14 |
+
return json.dumps({"error": "Input không được để trống"}, indent=2, ensure_ascii=False)
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
final_input = text_input
|
| 18 |
+
try:
|
| 19 |
+
stripped = text_input.strip()
|
| 20 |
+
if not stripped.startswith("{") and not stripped.startswith("["):
|
| 21 |
+
stripped = "{" + stripped + "}"
|
| 22 |
+
|
| 23 |
+
clean_input = stripped.replace("None", "null").replace("True", "true").replace("False", "false")
|
| 24 |
+
parsed_json = json.loads(clean_input)
|
| 25 |
+
|
| 26 |
+
if isinstance(parsed_json, dict) and "instances" in parsed_json:
|
| 27 |
+
final_input = parsed_json["instances"][0].get("raw_text", text_input)
|
| 28 |
+
else:
|
| 29 |
+
final_input = json.dumps(parsed_json)
|
| 30 |
+
except json.JSONDecodeError:
|
| 31 |
+
final_input = text_input
|
| 32 |
+
|
| 33 |
+
result = final_process_eme_technical_guided(final_input)
|
| 34 |
+
result_dict = result.model_dump() if hasattr(result, "model_dump") else result
|
| 35 |
+
return json.dumps(result_dict, indent=2, ensure_ascii=False)
|
| 36 |
+
|
| 37 |
+
except Exception as e:
|
| 38 |
+
return json.dumps({"error": str(e)}, indent=2, ensure_ascii=False)
|
| 39 |
+
|
| 40 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="yellow", secondary_hue="amber"),title="NLP") as demo:
|
| 41 |
+
gr.HTML(
|
| 42 |
+
"""
|
| 43 |
+
<div style="text-align: center; margin-bottom: 20px;">
|
| 44 |
+
<h1 style="font-size: 2.5em; margin-bottom: 5px;">Volta Energy Plan Parser</h1>
|
| 45 |
+
<p style="font-size: 1.2em; color: #666;">Energy Data Extraction Testing Interface.</p>
|
| 46 |
+
</div>
|
| 47 |
+
"""
|
| 48 |
+
)
|
| 49 |
+
with gr.Row():
|
| 50 |
+
with gr.Column(scale=1):
|
| 51 |
+
text_input = gr.Textbox(
|
| 52 |
+
label="Energy Plan Input",
|
| 53 |
+
placeholder="Paste the energy plan JSON here...",
|
| 54 |
+
lines=12
|
| 55 |
+
)
|
| 56 |
+
btn_submit = gr.Button("Submit", variant="primary")
|
| 57 |
+
|
| 58 |
+
with gr.Column(scale=1):
|
| 59 |
+
json_output = gr.Code(
|
| 60 |
+
label="Extracted Schema",
|
| 61 |
+
language="json",
|
| 62 |
+
lines=14
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
btn_submit.click(fn=parse_energy_plan_ui, inputs=text_input, outputs=json_output)
|
| 66 |
|
|
|
|
|
|
|
| 67 |
|
| 68 |
@asynccontextmanager
|
| 69 |
async def lifespan(app: FastAPI):
|
| 70 |
+
logger.info("--- [LIFESPAN] Volta Parser Service Online (Post-Processing Only) ---")
|
|
|
|
|
|
|
|
|
|
| 71 |
yield
|
| 72 |
+
logger.info("--- [LIFESPAN] Server stopped. ---")
|
|
|
|
| 73 |
|
|
|
|
| 74 |
app = FastAPI(title="Volta Energy Plan Parser API", lifespan=lifespan)
|
| 75 |
|
|
|
|
| 76 |
class PredictRequest(BaseModel):
|
| 77 |
instances: list
|
| 78 |
|
|
|
|
| 80 |
@app.post("/extract")
|
| 81 |
def predict(request: PredictRequest):
|
| 82 |
results = []
|
| 83 |
+
logger.info(f"--- [API REQUEST] Received {len(request.instances)} instances ---")
|
| 84 |
+
|
| 85 |
for instance in request.instances:
|
| 86 |
text = instance if isinstance(instance, str) else instance.get("raw_text", "")
|
| 87 |
+
|
| 88 |
+
# Tự động parse dict thành chuỗi nếu truyền cả object thay vì bọc trong raw_text
|
| 89 |
+
if isinstance(instance, dict) and "raw_text" not in instance:
|
| 90 |
+
text = json.dumps(instance)
|
| 91 |
+
|
| 92 |
+
if isinstance(text, str):
|
| 93 |
+
text = text.strip()
|
| 94 |
+
|
| 95 |
+
if not text:
|
| 96 |
+
results.append({"error": "Empty input resolved"})
|
| 97 |
+
continue
|
| 98 |
+
|
| 99 |
try:
|
| 100 |
res = final_process_eme_technical_guided(text)
|
| 101 |
+
results.append(res.model_dump() if hasattr(res, "model_dump") else res)
|
| 102 |
except Exception as e:
|
| 103 |
+
logger.error(f"--- [API ERROR] {str(e)} ---")
|
| 104 |
results.append({"error": str(e)})
|
| 105 |
+
|
| 106 |
return {"predictions": results}
|
| 107 |
|
| 108 |
@app.get("/health")
|
| 109 |
async def health():
|
| 110 |
return {"status": "healthy"}
|
| 111 |
|
| 112 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|
|
|
|
|
|