Spaces:
Sleeping
Sleeping
Toan2004-ai commited on
Commit ·
dfdc1de
1
Parent(s): 98ca760
add readme config
Browse files
main.py
CHANGED
|
@@ -1,115 +1,59 @@
|
|
| 1 |
-
from fastapi import FastAPI
|
| 2 |
-
from pydantic import BaseModel
|
| 3 |
-
import uvicorn
|
| 4 |
-
from engine import final_process_eme_technical_guided
|
| 5 |
-
from contextlib import asynccontextmanager
|
| 6 |
-
import logging
|
| 7 |
-
import json
|
| 8 |
import gradio as gr
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
def parse_energy_plan_ui(text_input):
|
|
|
|
| 14 |
if not text_input or not text_input.strip():
|
| 15 |
return json.dumps({"error": "Input không được để trống"}, indent=2, ensure_ascii=False)
|
| 16 |
|
| 17 |
try:
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
stripped = text_input.strip()
|
| 21 |
-
if not stripped.startswith("{") and not stripped.startswith("["):
|
| 22 |
-
stripped = "{" + stripped + "}"
|
| 23 |
-
|
| 24 |
-
clean_input = stripped.replace("None", "null").replace("True", "true").replace("False", "false")
|
| 25 |
-
parsed_json = json.loads(clean_input)
|
| 26 |
-
|
| 27 |
-
if isinstance(parsed_json, dict) and "instances" in parsed_json:
|
| 28 |
-
final_input = parsed_json["instances"][0].get("raw_text", text_input)
|
| 29 |
-
else:
|
| 30 |
-
final_input = json.dumps(parsed_json)
|
| 31 |
-
except json.JSONDecodeError:
|
| 32 |
-
final_input = text_input
|
| 33 |
|
|
|
|
| 34 |
result = final_process_eme_technical_guided(final_input)
|
|
|
|
|
|
|
| 35 |
result_dict = result.model_dump() if hasattr(result, "model_dump") else result
|
|
|
|
| 36 |
return json.dumps(result_dict, indent=2, ensure_ascii=False)
|
| 37 |
|
| 38 |
except Exception as e:
|
| 39 |
return json.dumps({"error": str(e)}, indent=2, ensure_ascii=False)
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
<div style="text-align: center; margin-bottom: 20px;">
|
| 45 |
-
<h1 style="font-size:
|
| 46 |
-
<p style="
|
| 47 |
</div>
|
| 48 |
-
|
| 49 |
-
|
| 50 |
with gr.Row():
|
|
|
|
| 51 |
with gr.Column(scale=1):
|
| 52 |
text_input = gr.Textbox(
|
| 53 |
-
label="Energy Plan Input",
|
| 54 |
placeholder="Paste the energy plan JSON here...",
|
| 55 |
-
lines=
|
| 56 |
)
|
| 57 |
-
|
| 58 |
-
|
| 59 |
|
|
|
|
| 60 |
with gr.Column(scale=1):
|
| 61 |
json_output = gr.Code(
|
| 62 |
-
label="Extracted Schema",
|
| 63 |
language="json",
|
| 64 |
-
lines=
|
| 65 |
)
|
| 66 |
-
btn_submit.click(fn=parse_energy_plan_ui, inputs=text_input, outputs=json_output)
|
| 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 |
-
|
| 79 |
-
@app.post("/predict")
|
| 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 |
-
|
| 93 |
-
|
| 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="/")
|
| 113 |
|
|
|
|
| 114 |
if __name__ == "__main__":
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import json
|
| 3 |
+
from engine import final_process_eme_technical_guided
|
|
|
|
| 4 |
|
| 5 |
def parse_energy_plan_ui(text_input):
|
| 6 |
+
"""Hàm xử lý logic trích xuất dữ liệu"""
|
| 7 |
if not text_input or not text_input.strip():
|
| 8 |
return json.dumps({"error": "Input không được để trống"}, indent=2, ensure_ascii=False)
|
| 9 |
|
| 10 |
try:
|
| 11 |
+
# Xử lý input đầu vào
|
| 12 |
+
final_input = text_input.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# Gọi engine xử lý (đảm bảo engine.py không chứa code nặng ở global)
|
| 15 |
result = final_process_eme_technical_guided(final_input)
|
| 16 |
+
|
| 17 |
+
# Chuyển đổi kết quả sang dict
|
| 18 |
result_dict = result.model_dump() if hasattr(result, "model_dump") else result
|
| 19 |
+
|
| 20 |
return json.dumps(result_dict, indent=2, ensure_ascii=False)
|
| 21 |
|
| 22 |
except Exception as e:
|
| 23 |
return json.dumps({"error": str(e)}, indent=2, ensure_ascii=False)
|
| 24 |
|
| 25 |
+
# Tạo giao diện
|
| 26 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="yellow", secondary_hue="amber"), title="Volta Parser") as demo:
|
| 27 |
+
gr.HTML("""
|
| 28 |
<div style="text-align: center; margin-bottom: 20px;">
|
| 29 |
+
<h1 style="font-size: 2em; margin-bottom: 5px;">Volta Energy Plan Parser</h1>
|
| 30 |
+
<p style="color: #666;">Dán JSON hợp đồng điện để trích xuất dữ liệu chi tiết</p>
|
| 31 |
</div>
|
| 32 |
+
""")
|
| 33 |
+
|
| 34 |
with gr.Row():
|
| 35 |
+
# Cột Input
|
| 36 |
with gr.Column(scale=1):
|
| 37 |
text_input = gr.Textbox(
|
| 38 |
+
label="Energy Plan Input (JSON)",
|
| 39 |
placeholder="Paste the energy plan JSON here...",
|
| 40 |
+
lines=15
|
| 41 |
)
|
| 42 |
+
# Nút Submit nằm gọn trong cột
|
| 43 |
+
btn_submit = gr.Button("Submit", variant="primary")
|
| 44 |
|
| 45 |
+
# Cột Output
|
| 46 |
with gr.Column(scale=1):
|
| 47 |
json_output = gr.Code(
|
| 48 |
+
label="Extracted Schema (JSON Output)",
|
| 49 |
language="json",
|
| 50 |
+
lines=17
|
| 51 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
# Sự kiện click
|
| 54 |
+
btn_submit.click(fn=parse_energy_plan_ui, inputs=text_input, outputs=json_output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
# Chạy ứng dụng
|
| 57 |
if __name__ == "__main__":
|
| 58 |
+
# Server port 7860 là mặc định của Hugging Face Spaces
|
| 59 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|