Toan2004-ai commited on
Commit
98ca760
·
1 Parent(s): fc85478

add readme config

Browse files
Files changed (1) hide show
  1. main.py +100 -13
main.py CHANGED
@@ -1,28 +1,115 @@
1
- import gradio as gr
2
- import json
 
3
  from engine import final_process_eme_technical_guided
 
 
 
 
 
 
 
4
 
5
- # Hàm xử lý giao diện
6
  def parse_energy_plan_ui(text_input):
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
  try:
10
- # ... (giữ nguyên logic xử lý của bạn) ...
11
- result = final_process_eme_technical_guided(text_input)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  result_dict = result.model_dump() if hasattr(result, "model_dump") else result
13
  return json.dumps(result_dict, indent=2, ensure_ascii=False)
 
14
  except Exception as e:
15
  return json.dumps({"error": str(e)}, indent=2, ensure_ascii=False)
16
 
17
- # Giao diện Gradio
18
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="yellow", secondary_hue="amber"), title="NLP") as demo:
19
- gr.HTML("<div style='text-align: center;'><h1>Volta Energy Plan Parser</h1></div>")
 
 
 
 
 
 
20
  with gr.Row():
21
- text_input = gr.Textbox(label="Energy Plan Input", lines=12)
22
- json_output = gr.Code(label="Extracted Schema", language="json", lines=14)
23
- btn_submit = gr.Button("Submit", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
24
  btn_submit.click(fn=parse_energy_plan_ui, inputs=text_input, outputs=json_output)
25
 
26
- # CHỈ CẦN DÒNG NÀY ĐỂ CHẠY GRADIO
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  if __name__ == "__main__":
28
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
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
+ logging.basicConfig(level=logging.INFO)
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
+ final_input = text_input
19
+ try:
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
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="yellow", secondary_hue="amber"),title="NLP") as demo:
42
+ gr.HTML(
43
+ """
44
+ <div style="text-align: center; margin-bottom: 20px;">
45
+ <h1 style="font-size: 2.5em; margin-bottom: 5px;">Volta Energy Plan Parser</h1>
46
+ <p style="font-size: 1.2em; color: #666;">Energy Data Extraction Testing Interface.</p>
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=12
56
+ )
57
+ with gr.Row():
58
+ btn_submit = gr.Button("Submit", variant="primary", scale=1)
59
+
60
+ with gr.Column(scale=1):
61
+ json_output = gr.Code(
62
+ label="Extracted Schema",
63
+ language="json",
64
+ lines=14
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
+ 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="/")
113
+
114
  if __name__ == "__main__":
115
+ uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=False)