huy-le commited on
Commit
87f48b8
·
verified ·
1 Parent(s): 212ad5b

Them nhanh video + fusion, chuyen mau, xu ly file loi (model tai tu repo private)

Browse files
Files changed (9) hide show
  1. README.md +63 -29
  2. app.py +260 -44
  3. dinov3_encoder.py +244 -0
  4. inference.py +278 -80
  5. requirements.txt +6 -2
  6. static/index.html +279 -104
  7. swin_fusion.py +720 -0
  8. tools/precompute_demo.py +100 -0
  9. video_pipeline.py +263 -0
README.md CHANGED
@@ -9,66 +9,100 @@ python_version: "3.10"
9
  app_file: app.py
10
  pinned: false
11
  license: cc-by-nc-4.0
12
- short_description: Kiểm tra hành vi lái xe từ dữ liệu cảm biến (thử nghiệm)
13
  ---
14
 
15
  # Web kiểm tra hành vi lái xe (bản thử nghiệm)
16
 
17
- Web giúp nhân viên an toàn của công ty xe dịch vụ xem lại một chuyến đi của tài xế. Người dùng tải lên dữ liệu cảm biến của chuyến, AI chia chuyến thành các đoạn 5 giây và cho biết mỗi đoạn giống kiểu lái nào nhất: **Bình thường**, **Lái xe hung hăng** hay **Dấu hiệu buồn ngủ**. Web tổng hợp thành kết luận, dòng thời gian, danh sách đoạn cần xem lại và biểu đồ chi tiết.
18
 
19
- Bản này chỉ dùng **nhánh 1D** của DuST (1D Swin Transformer trên gia tốc kế). Nhánh video (DINOv3) sẽ thêm ở phiên bản sau.
 
 
 
 
 
 
20
 
21
  ## Cấu trúc
22
 
23
  | File | Vai trò |
24
  |---|---|
25
- | `app.py` | FastAPI: trả trang web, `GET /api/status`, `POST /api/analyze` |
26
- | `inference.py` | Làm sạch dữ liệu và cắt cửa sổ giống hệt lúc train, chạy model, gom các đoạn bất thường |
27
- | `swin1d.py` | Bản sao nguyên vẹn `models/SwinTransformer_cls.py` để thư mục này tự chạy được |
28
- | `static/index.html` | Giao diện, một file HTML + JavaScript thuần, không cần build |
29
- | `weights/` | `final_1d.pth` + `kine_norm_stats.json` (xem `weights/README.txt`) |
30
- | `requirements.txt` | Thư viện cho Space (SDK Gradio tự cài thêm gradio, fastapi, uvicorn) |
31
- | `Dockerfile` | Chỉ dùng nếu sau này chuyển sang Space SDK Docker (gói trả phí). Space SDK Gradio bỏ qua file này |
32
 
33
  ## Dữ liệu đầu vào
34
 
35
- - **Bắt buộc**: `RAW_ACCELEROMETERS.txt` theo định dạng UAH-DriveSet (11 cột, ~10 Hz).
36
- - **Không bắt buộc**: `RAW_GPS.txt` (12 cột). Có file này thì web hiện thêm quãng đường, tốc độ cao nhất và biểu đồ tốc độ. GPS không được đưa vào model.
37
- - Có thể chọn cả thư mục chuyến đi, web tự tìm 2 file trên.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  ## Chạy trên máy
40
 
41
  ```bash
42
  cd web
43
- pip install -r requirements.txt fastapi uvicorn python-multipart
44
- # chép final_1d.pth và kine_norm_stats.json vào web/weights/
45
  python app.py
46
  ```
47
 
48
- Mở http://localhost:7860.
49
 
50
- ## Deploy lên Hugging Face Spaces (miễn phí)
51
 
52
- 1. Tạo tài khoản tại huggingface.co, rồi tạo Space mới: **SDK = Gradio** (SDK Docker cần gói trả phí). Tài khoản miễn phí mặc định nhận phần cứng **ZeroGPU** và không hạ xuống CPU basic được; web vẫn chạy bình thường trên đó (model chạy bằng CPU của container). ZeroGPU luôn dùng **Python 3.10**, bắt buộc có ít nhất 1 hàm `@spaces.GPU` và chỉ nhận một số bản torch (vd. 2.12.1) — `app.py` và `requirements.txt` đã xử lý cả ba. Nên chọn **Private** ở giai đoạn thử nghiệm. Web không dùng giao diện Gradio: `app.py` tự chạy FastAPI ở cổng 7860, Space chỉ cần môi trường Python mà SDK Gradio cung cấp. Phần cấu hình ở đầu file README này (`sdk`, `sdk_version`, `python_version`, `license`) sẽ ghi đè lựa chọn trên trang tạo Space.
53
- 2. Tạo access token có quyền *write* (Settings → Access Tokens).
54
- 3. Trên máy, mở terminal ở thư mục `DUST/` rồi upload cả thư mục `web/` (kể cả `weights/`):
55
 
56
  ```bash
57
- pip install -U huggingface_hub
58
- huggingface-cli login
59
- huggingface-cli upload <tên-tài-khoản>/<tên-space> web . --repo-type=space
60
  ```
61
 
62
- File model ~760 MB được tự chuyển qua Git LFS.
63
- 4. Space tự cài thư viện và khởi động (lần đầu khoảng 5–10 phút, theo dõi ở tab Logs), xong sẽ có link dạng `https://<tên-tài-khoản>-<tên-space>.hf.space`.
64
 
65
  Space miễn phí sẽ ngủ sau 48 giờ không có người dùng. Lần mở tiếp theo mất khoảng 1–2 phút để khởi động lại.
66
 
67
  ## Giới hạn cần biết
68
 
69
- - **Bản quyền dữ liệu**: model được train trên UAH-DriveSet. License của bộ dữ liệu **cấm dùng cho mục đích thương mại**, kể cả model train từ nó, và **cấm phát tán lại dữ liệu**. Vì vậy web không kèm file dữ liệu mẫu nào. Để dùng thật cho công ty xe dịch vụ cần train lại trên dữ liệu của chính công ty.
70
- - **Nhãn**: UAH gán một nhãn cho cả chuyến (tài xế được yêu cầu lái theo một kiểu). Model học từ nhãn đó, nên kết quả từng đoạn 5 giây chỉ là mức "giống kiểu lái nào", không phải phát hiện sự kiện đã được kiểm chứng.
71
- - **Định dạng**: chỉ nhận file theo định dạng UAH-DriveSet. Dữ liệu từ thiết bị khác cần chuyển đổi về đúng cột và tần số.
72
- - **Ngưỡng hiển thị** (đánh dấu đoạn khi AI chắc chắn ≥ 60%, mức "Cao" khi ≥ 80%, kết luận theo tỉ lệ 15% / 40%) là ngưỡng đặt tay cho bản thử nghiệm, chưa được hiệu chỉnh trên dữ liệu.
73
 
74
  Trích dẫn dữ liệu: E. Romera, L.M. Bergasa, R. Arroyo, "Need Data for Driving Behavior Analysis? Presenting the Public UAH-DriveSet", IEEE ITSC 2016.
 
9
  app_file: app.py
10
  pinned: false
11
  license: cc-by-nc-4.0
12
+ short_description: Kiểm tra hành vi lái xe từ cảm biến và video (thử nghiệm)
13
  ---
14
 
15
  # Web kiểm tra hành vi lái xe (bản thử nghiệm)
16
 
17
+ Web giúp nhân viên an toàn của công ty xe dịch vụ xem lại một chuyến đi của tài xế. AI chia chuyến thành các đoạn 5 giây và cho biết mỗi đoạn giống kiểu lái nào nhất: **Bình thường**, **Lái xe hung hăng** hay **Dấu hiệu buồn ngủ**. Web tổng hợp thành kết luận, dòng thời gian, danh sách đoạn cần xem lại, khung hình video và biểu đồ chi tiết.
18
 
19
+ Web chạy cả 3 model của DuST-DINOv3 và cho xem kết quả theo từng cách:
20
+
21
+ | Cách phân tích | Model | File trong `weights/` |
22
+ |---|---|---|
23
+ | Chỉ cảm biến | 1D Swin (Stage 2) | `final_1d.pth` + `kine_norm_stats.json` |
24
+ | Chỉ video | DINOv3 ViT-S/16 + Temporal Transformer (Stage 1) | `video_3d.pth` |
25
+ | Kết hợp | 1D Swin fusion (Stage 4) | `fusion.pth` |
26
 
27
  ## Cấu trúc
28
 
29
  | File | Vai trò |
30
  |---|---|
31
+ | `app.py` | FastAPI: trang web, kiểm tra file khi upload, hàng đợi xử lý, hàm GPU cho ZeroGPU |
32
+ | `inference.py` | Đọc và kiểm tra file cảm biến, làm sạch và cắt đoạn giống lúc train, chạy 3 model, tổng hợp kết quả |
33
+ | `video_pipeline.py` | Đồng bộ video với cảm biến, lấy 77 frame mỗi đoạn, chạy DINOv3, tạo ảnh thu nhỏ |
34
+ | `swin1d.py`, `swin_fusion.py`, `dinov3_encoder.py` | Bản sao nguyên vẹn mã model của project, để thư mục này tự chạy được |
35
+ | `static/index.html` | Giao diện, một file HTML + JavaScript thuần |
36
+ | `tools/precompute_demo.py` | Tạo dữ liệu chuyến mẫu (chạy 1 lần trên máy) |
37
+ | `weights/` | 4 file model ở bảng trên |
38
 
39
  ## Dữ liệu đầu vào
40
 
41
+ | File | Bắt buộc | Giới hạn |
42
+ |---|---|---|
43
+ | `RAW_ACCELEROMETERS.txt` (UAH-DriveSet, 11 cột) | Có | 20 MB |
44
+ | `RAW_GPS.txt` (12 cột) | Không. Dùng để hiện quãng đường, tốc độ và hỗ trợ đồng bộ video | 20 MB |
45
+ | Video hành trình `.mp4` | Không. Có video thì chạy thêm nhánh video và fusion | 300 MB |
46
+
47
+ - Có thể chọn cả thư mục chuyến đi, web tự tìm 3 file trên.
48
+ - Chuyến đi phải dài từ 1 phút đến 2 giờ.
49
+ - **Nhánh video** cần đồng bộ được video với cảm biến (cùng cách kiểm chứng như lúc tạo dữ liệu train). Không đồng bộ được thì web chỉ hiện kết quả cảm biến và báo rõ lý do.
50
+ - **DINOv3** chạy trên GPU qua ZeroGPU. Nếu hết hạn mức GPU, web chuyển sang CPU và chỉ phân tích video 24 đoạn trải đều trong chuyến (đổi bằng biến môi trường `VIDEO_CPU_MAX_WINDOWS`).
51
+
52
+ ## Các trường hợp lỗi được xử lý
53
+
54
+ | Trường hợp | Kết quả |
55
+ |---|---|
56
+ | File quá lớn | Từ chối ngay trên trình duyệt; máy chủ đọc theo từng phần và dừng khi vượt giới hạn (HTTP 413) |
57
+ | Sai loại file (video ở ô văn bản, `.exe`, file nhị phân, sai mã hoá) | Báo lỗi rõ ô nào sai (HTTP 400) |
58
+ | Sai số cột, dùng dấu phẩy, giá trị không phải số, NaN | Báo dòng bị lỗi |
59
+ | Chọn nhầm file GPS và cảm biến | Nhận ra và gợi ý file đúng |
60
+ | Chuyến dưới 1 phút hoặc trên 2 giờ, không còn đoạn hợp lệ | Báo lý do |
61
+ | Video hỏng, không mở được, quá ngắn hoặc quá dài | Báo lỗi trước khi phân tích |
62
+ | Video không đồng bộ được hoặc không trùng thời gian với cảm biến | Chỉ hiện kết quả cảm biến, kèm cảnh báo |
63
+ | Nhiều người cùng phân tích | Xử lý lần lượt, hiện thứ tự chờ; quá 3 yêu cầu thì báo bận (HTTP 429) |
64
+ | Mất mạng, phân tích quá 20 phút | Thông báo và cho phép thử lại |
65
+
66
+ ## Chuyến mẫu
67
+
68
+ Nút "Phân tích chuyến mẫu" phân tích sẵn một chuyến của tài xế D6 (tài xế không có trong dữ liệu train). Dữ liệu chuyến mẫu nằm trong **dataset private** `huy-le/checking-driver-demo`, Space tải về lúc khởi động bằng secret `HF_TOKEN`. Web hiển thị khung hình video nhưng không có đường nào tải file gốc. Đặc trưng DINOv3 của chuyến mẫu được tính sẵn để demo luôn chạy được; Temporal Transformer, nhánh video và fusion vẫn chạy trực tiếp mỗi lần bấm.
69
+
70
+ Tạo lại chuyến mẫu:
71
+
72
+ ```bash
73
+ cd web
74
+ python tools/precompute_demo.py --trip "<thư mục chuyến UAH>" --out demo
75
+ hf upload huy-le/checking-driver-demo demo . --repo-type=dataset --private
76
+ ```
77
 
78
  ## Chạy trên máy
79
 
80
  ```bash
81
  cd web
82
+ pip install -r requirements.txt fastapi uvicorn python-multipart huggingface_hub
 
83
  python app.py
84
  ```
85
 
86
+ Mở http://localhost:7860. Nếu có thư mục `web/demo/` thì nút chuyến mẫu hoạt động.
87
 
88
+ ## Deploy lên Hugging Face Spaces
89
 
90
+ 1. Space dùng **SDK Gradio**, phần cứng **ZeroGPU** (mặc định của tài khoản miễn phí). ZeroGPU luôn dùng Python 3.10, cần ít nhất 1 hàm `@spaces.GPU` và chỉ nhận một số bản torch; `app.py` và `requirements.txt` đã xử lý.
91
+ 2. Upload thư mục `web/` (trừ `demo/`, vì dữ liệu chuyến mẫu chỉ nằm trong dataset private):
 
92
 
93
  ```bash
94
+ hf upload huy-le/Checking-Driver web . --repo-type=space --exclude "demo/*" --exclude "__pycache__/*"
 
 
95
  ```
96
 
97
+ 3. Trong Settings của Space, thêm secret `HF_TOKEN` (token có quyền đọc dataset private).
 
98
 
99
  Space miễn phí sẽ ngủ sau 48 giờ không có người dùng. Lần mở tiếp theo mất khoảng 1–2 phút để khởi động lại.
100
 
101
  ## Giới hạn cần biết
102
 
103
+ - **Model đang dùng là bản thử nghiệm**: video lấy checkpoint epoch 18 (val 57.5%), fusion epoch 17 (val 42.5%), cảm biến val 32.5%. Kết quả chưa đủ tin cậy để đánh giá tài xế.
104
+ - **Bản quyền dữ liệu**: UAH-DriveSet chỉ dùng phi thương mại và cấm phát tán lại dữ liệu. Để dùng thật cho công ty xe dịch vụ cần train lại trên dữ liệu của chính công ty.
105
+ - **Nhãn**: UAH gán một nhãn cho cả chuyến, nên kết quả từng đoạn 5 giây chỉ là mức "giống kiểu lái nào".
106
+ - **Ngưỡng hiển thị** (đánh dấu đoạn khi AI chắc chắn ≥ 60%, mức "Cao" khi ≥ 80%, kết luận theo tỉ lệ 15% / 40%) là ngưỡng đặt tay, chưa được hiệu chỉnh.
107
 
108
  Trích dẫn dữ liệu: E. Romera, L.M. Bergasa, R. Arroyo, "Need Data for Driving Behavior Analysis? Presenting the Public UAH-DriveSet", IEEE ITSC 2016.
app.py CHANGED
@@ -1,38 +1,219 @@
1
  """
2
- Web kiểm tra hành vi lái xe (bản thử nghiệm, nhánh 1D của DuST).
3
 
4
- Chạy trên máy: uvicorn app:app --port 7860
5
- Deploy: Hugging Face Spaces (Docker), xem README.md
 
 
 
 
 
 
6
  """
7
 
8
  import os
9
 
10
- from fastapi import FastAPI, File, HTTPException, UploadFile
11
- from fastapi.responses import FileResponse
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  from starlette.concurrency import run_in_threadpool
13
 
14
- from inference import Analyzer, InputError
 
15
 
16
  HERE = os.path.dirname(os.path.abspath(__file__))
17
  WEIGHTS_DIR = os.environ.get('WEIGHTS_DIR', os.path.join(HERE, 'weights'))
18
- MAX_UPLOAD_MB = 20
 
 
 
 
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  app = FastAPI(title='Kiểm tra hành vi lái xe')
21
- analyzer = Analyzer(WEIGHTS_DIR)
22
 
23
- # Space phần cứng ZeroGPU bắt buộc có ít nhất 1 hàm @spaces.GPU lúc khởi động, nếu không sẽ báo
24
- # "No @spaces.GPU function detected". Model 1D chạy đủ nhanh trên CPU (~4 s/chuyến) nên chỉ khai báo
25
- # một hàm giữ chỗ. Gói `spaces` chỉ có trên Hugging Face; chạy trên máy thì bỏ qua.
26
- try:
27
- import spaces
 
28
 
29
- @spaces.GPU
30
- def _zerogpu_placeholder():
31
- return None
32
- except ImportError:
33
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  @app.get('/')
37
  def index():
38
  return FileResponse(os.path.join(HERE, 'static', 'index.html'))
@@ -40,44 +221,79 @@ def index():
40
 
41
  @app.get('/api/status')
42
  def status():
43
- return {'ready': analyzer.ready, 'message': analyzer.error or 'Sẵn sàng'}
44
-
45
-
46
- async def _read_text(f: UploadFile, name: str):
47
- data = await f.read()
48
- if len(data) > MAX_UPLOAD_MB * 1024 * 1024:
49
- raise HTTPException(400, f'{name} quá lớn (tối đa {MAX_UPLOAD_MB} MB).')
50
- try:
51
- return data.decode('utf-8')
52
- except UnicodeDecodeError:
53
- raise HTTPException(400, f'{name} không phải file văn bản.')
54
 
55
 
56
  @app.post('/api/analyze')
57
- async def analyze(acc_file: UploadFile = File(...), gps_file: UploadFile | None = File(None)):
 
 
 
58
  if not analyzer.ready:
59
  raise HTTPException(503, 'Hệ thống chưa có model. ' + (analyzer.error or ''))
60
- acc_text = await _read_text(acc_file, 'File cảm biến chuyển động')
61
- gps_text = await _read_text(gps_file, 'File GPS') if gps_file and gps_file.filename else None
62
  try:
63
- # chạy model trong thread riêng để không chặn server trong vài giây suy luận
64
- return await run_in_threadpool(analyzer.analyze, acc_text, gps_text)
65
  except InputError as e:
66
  raise HTTPException(400, str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
 
69
  if __name__ == '__main__':
70
- # Hugging Face Space (SDK Gradio) khởi động bằng `python app.py` và chờ web ở cổng 7860.
71
- # Web này là FastAPI + HTML riêng, nên tự chạy uvicorn thay vì dùng giao diện Gradio.
72
  import uvicorn
73
 
74
- # ZeroGPU chỉ "báo cáo khởi động" bên trong gr.Blocks.launch() (gói spaces gắn vào hàm đó).
75
- # Web này không gọi launch() nên gọi trực tiếp bước khởi động của spaces trước khi chạy uvicorn.
76
- try:
77
- import spaces.zero as _zero
78
- if hasattr(_zero, 'startup'):
79
- _zero.startup()
80
- except ImportError:
81
- pass
 
82
 
83
  uvicorn.run(app, host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
 
1
  """
2
+ Web kiểm tra hành vi lái xe (bản thử nghiệm DuST-DINOv3: cảm biến + video + fusion).
3
 
4
+ Chạy trên máy: python app.py (mở http://localhost:7860)
5
+ Deploy: Hugging Face Spaces (SDK Gradio, phần cứng ZeroGPU), xem README.md
6
+
7
+ Luồng xử lý:
8
+ POST /api/analyze -> kiểm tra file ngay (dung lượng, loại file, nội dung); hợp lệ thì đưa vào hàng đợi
9
+ POST /api/demo -> đưa "chuyến mẫu" vào hàng đợi (không cần upload)
10
+ GET /api/job/{id} -> trạng thái, tiến độ, vị trí trong hàng đợi, kết quả
11
+ Mỗi lúc chỉ xử lý 1 chuyến (1 luồng worker), tối đa MAX_PENDING yêu cầu đang chờ.
12
  """
13
 
14
  import os
15
 
16
+ # Trên Space ZeroGPU, `spaces` phải được import trước mọi thứ có thể khởi tạo CUDA.
17
+ try:
18
+ import spaces
19
+ except ImportError:
20
+ spaces = None
21
+
22
+ import queue
23
+ import shutil
24
+ import tempfile
25
+ import threading
26
+ import time
27
+ import uuid
28
+
29
+ from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile
30
+ from fastapi.responses import FileResponse, JSONResponse
31
  from starlette.concurrency import run_in_threadpool
32
 
33
+ import video_pipeline as vp
34
+ from inference import MAX_TRIP_SEC, MIN_TRIP_SEC, Analyzer, InputError, load_sensors
35
 
36
  HERE = os.path.dirname(os.path.abspath(__file__))
37
  WEIGHTS_DIR = os.environ.get('WEIGHTS_DIR', os.path.join(HERE, 'weights'))
38
+ DEMO_DIR = os.environ.get('DEMO_DIR', os.path.join(HERE, 'demo'))
39
+ DEMO_REPO = os.environ.get('DEMO_REPO', 'huy-le/checking-driver-demo') # dataset PRIVATE chứa chuyến mẫu
40
+ # Space miễn phí giới hạn 1 GB, không chứa nổi 3 model (~1.6 GB) -> model nằm ở model repo PRIVATE riêng
41
+ WEIGHTS_REPO = os.environ.get('WEIGHTS_REPO', 'huy-le/checking-driver-weights')
42
+ WEIGHT_FILES = ['final_1d.pth', 'kine_norm_stats.json', 'video_3d.pth', 'fusion.pth']
43
 
44
+ TEXT_MAX_MB = 20
45
+ VIDEO_MAX_MB = 300
46
+ TOTAL_MAX_BYTES = (2 * TEXT_MAX_MB + VIDEO_MAX_MB + 2) * 1024 * 1024
47
+ TEXT_EXT = {'.txt', '.csv'}
48
+ VIDEO_EXT = {'.mp4', '.mov', '.avi', '.mkv', '.m4v'}
49
+ MAX_PENDING = 3 # số yêu cầu tối đa đang chờ + đang chạy
50
+ JOB_TTL_SEC = 1800 # kết quả giữ trong 30 phút
51
+
52
+
53
+ def _fetch_demo():
54
+ """Tải chuyến mẫu từ dataset private (cần secret HF_TOKEN trên Space). Lỗi thì web vẫn chạy, chỉ tắt nút demo."""
55
+ if os.path.isfile(os.path.join(DEMO_DIR, 'meta.json')):
56
+ return
57
+ token = os.environ.get('HF_TOKEN')
58
+ if not token:
59
+ return
60
+ try:
61
+ from huggingface_hub import snapshot_download
62
+ snapshot_download(repo_id=DEMO_REPO, repo_type='dataset', local_dir=DEMO_DIR, token=token)
63
+ except Exception as e:
64
+ print(f'[demo] không tải được chuyến mẫu: {e}')
65
+
66
+
67
+ def _fetch_weights():
68
+ """Tải model từ model repo private nếu thư mục weights/ còn thiếu file (luôn đúng khi chạy trên Space)."""
69
+ if all(os.path.isfile(os.path.join(WEIGHTS_DIR, f)) for f in WEIGHT_FILES):
70
+ return
71
+ token = os.environ.get('HF_TOKEN')
72
+ if not token:
73
+ print('[weights] thiếu file model và không có HF_TOKEN để tải')
74
+ return
75
+ try:
76
+ from huggingface_hub import snapshot_download
77
+ snapshot_download(repo_id=WEIGHTS_REPO, repo_type='model', local_dir=WEIGHTS_DIR, token=token,
78
+ allow_patterns=WEIGHT_FILES)
79
+ except Exception as e:
80
+ print(f'[weights] không tải được model: {e}')
81
+
82
+
83
+ _fetch_weights()
84
+ _fetch_demo()
85
  app = FastAPI(title='Kiểm tra hành vi lái xe')
86
+ analyzer = Analyzer(WEIGHTS_DIR, demo_dir=DEMO_DIR)
87
 
88
+ # ZeroGPU: chạy DINOv3 trên GPU. Space ZeroGPU cũng bắt buộc có ít nhất 1 hàm @spaces.GPU.
89
+ GPU_FN = None
90
+ if spaces is not None:
91
+ @spaces.GPU(duration=150)
92
+ def _gpu_backbone(frames_path, rows):
93
+ return vp.backbone_cls(analyzer.video, frames_path, rows, device='cuda')
94
 
95
+ if analyzer.video is not None:
96
+ GPU_FN = _gpu_backbone
97
+
98
+
99
+ # ----------------------------------------------------------------------------
100
+ # Hàng đợi xử lý
101
+ # ----------------------------------------------------------------------------
102
+ JOBS = {}
103
+ LOCK = threading.Lock()
104
+ QUEUE = queue.Queue()
105
+
106
+
107
+ def _cleanup():
108
+ now = time.time()
109
+ with LOCK:
110
+ for jid in [j for j, v in JOBS.items() if v['status'] in ('done', 'error') and now - v['created'] > JOB_TTL_SEC]:
111
+ JOBS.pop(jid, None)
112
+
113
+
114
+ def _worker():
115
+ while True:
116
+ jid = QUEUE.get()
117
+ job = JOBS.get(jid)
118
+ if job is None:
119
+ continue
120
+ job['status'] = 'running'
121
+ progress = lambda msg: job.__setitem__('progress', msg)
122
+ try:
123
+ if job['kind'] == 'demo':
124
+ sens = analyzer.demo_sensors()
125
+ job['result'] = analyzer.analyze(sens, demo=True, progress=progress)
126
+ else:
127
+ job['result'] = analyzer.analyze(job['sens'], video=job.get('video'), progress=progress, gpu_fn=GPU_FN)
128
+ job['status'] = 'done'
129
+ job['progress'] = 'Xong'
130
+ except InputError as e:
131
+ job.update(status='error', error=str(e))
132
+ except Exception as e: # lỗi bất ngờ: báo chung, ghi chi tiết ra log của Space
133
+ print(f'[job {jid}] lỗi: {e!r}')
134
+ job.update(status='error', error='Có lỗi khi phân tích chuyến đi này. Hãy thử lại hoặc chọn file khác.')
135
+ finally:
136
+ job.pop('sens', None)
137
+ if job.get('tmp'):
138
+ shutil.rmtree(job['tmp'], ignore_errors=True)
139
+ job['created'] = time.time()
140
+ QUEUE.task_done()
141
 
142
 
143
+ threading.Thread(target=_worker, daemon=True).start()
144
+
145
+
146
+ def _submit(kind, **payload):
147
+ _cleanup()
148
+ with LOCK:
149
+ pending = sum(1 for v in JOBS.values() if v['status'] in ('queued', 'running'))
150
+ if pending >= MAX_PENDING:
151
+ raise HTTPException(429, 'Hệ thống đang bận phân tích các chuyến khác. Vui lòng thử lại sau vài phút.')
152
+ jid = uuid.uuid4().hex
153
+ JOBS[jid] = dict(kind=kind, status='queued', progress='Đang chờ đến lượt…', created=time.time(), **payload)
154
+ QUEUE.put(jid)
155
+ return {'job_id': jid}
156
+
157
+
158
+ # ----------------------------------------------------------------------------
159
+ # Giới hạn dung lượng
160
+ # ----------------------------------------------------------------------------
161
+ @app.middleware('http')
162
+ async def limit_body(request: Request, call_next):
163
+ if request.method == 'POST':
164
+ cl = request.headers.get('content-length')
165
+ if cl and cl.isdigit() and int(cl) > TOTAL_MAX_BYTES:
166
+ return JSONResponse(status_code=413, content={
167
+ 'detail': f'Dữ liệu tải lên quá lớn. Giới hạn: file văn bản {TEXT_MAX_MB} MB, video {VIDEO_MAX_MB} MB.'})
168
+ return await call_next(request)
169
+
170
+
171
+ def _ext(f):
172
+ return os.path.splitext(f.filename or '')[1].lower()
173
+
174
+
175
+ async def _read_text(f, name):
176
+ ext = _ext(f)
177
+ if ext in VIDEO_EXT:
178
+ raise HTTPException(400, f'{name}: đây là file video. Hãy chọn file video ở ô "Video hành trình".')
179
+ if ext not in TEXT_EXT:
180
+ raise HTTPException(400, f'{name}: chỉ nhận file .txt (định dạng UAH-DriveSet).')
181
+ data = bytearray()
182
+ while chunk := await f.read(1 << 20):
183
+ data.extend(chunk)
184
+ if len(data) > TEXT_MAX_MB * 1024 * 1024:
185
+ raise HTTPException(413, f'{name} quá lớn (tối đa {TEXT_MAX_MB} MB).')
186
+ return bytes(data)
187
+
188
+
189
+ async def _save_video(f, folder):
190
+ ext = _ext(f)
191
+ if ext not in VIDEO_EXT:
192
+ raise HTTPException(400, f'Video: định dạng "{ext or "không rõ"}" không được hỗ trợ. Hãy chọn file .mp4.')
193
+ path = os.path.join(folder, 'video' + ext)
194
+ size = 0
195
+ with open(path, 'wb') as out:
196
+ while chunk := await f.read(1 << 20):
197
+ size += len(chunk)
198
+ if size > VIDEO_MAX_MB * 1024 * 1024:
199
+ raise HTTPException(413, f'Video quá lớn (tối đa {VIDEO_MAX_MB} MB).')
200
+ out.write(chunk)
201
+ if size == 0:
202
+ raise HTTPException(400, 'Video trống.')
203
+ try:
204
+ _, _, dur = await run_in_threadpool(vp.probe_video, path)
205
+ except ValueError as e:
206
+ raise HTTPException(400, f'Video: {e}')
207
+ if dur < MIN_TRIP_SEC:
208
+ raise HTTPException(400, f'Video quá ngắn ({dur:.0f} giây). Cần ít nhất {MIN_TRIP_SEC // 60} phút.')
209
+ if dur > MAX_TRIP_SEC + 600:
210
+ raise HTTPException(400, f'Video quá dài ({dur / 3600:.1f} giờ). Hệ thống chỉ nhận tối đa {MAX_TRIP_SEC // 3600} giờ.')
211
+ return path
212
+
213
+
214
+ # ----------------------------------------------------------------------------
215
+ # API
216
+ # ----------------------------------------------------------------------------
217
  @app.get('/')
218
  def index():
219
  return FileResponse(os.path.join(HERE, 'static', 'index.html'))
 
221
 
222
  @app.get('/api/status')
223
  def status():
224
+ s = analyzer.status()
225
+ s.update(gpu=GPU_FN is not None, limits=dict(text_mb=TEXT_MAX_MB, video_mb=VIDEO_MAX_MB))
226
+ return s
 
 
 
 
 
 
 
 
227
 
228
 
229
  @app.post('/api/analyze')
230
+ async def analyze(acc_file: UploadFile = File(...),
231
+ gps_file: UploadFile | None = File(None),
232
+ video_file: UploadFile | None = File(None),
233
+ trip_name: str = Form('')):
234
  if not analyzer.ready:
235
  raise HTTPException(503, 'Hệ thống chưa có model. ' + (analyzer.error or ''))
236
+ acc = await _read_text(acc_file, 'File cảm biến chuyển động')
237
+ gps = await _read_text(gps_file, 'File GPS') if gps_file is not None and gps_file.filename else None
238
  try:
239
+ sens = await run_in_threadpool(load_sensors, acc, gps)
 
240
  except InputError as e:
241
  raise HTTPException(400, str(e))
242
+ tmp, video = None, None
243
+ if video_file is not None and video_file.filename:
244
+ tmp = tempfile.mkdtemp(prefix='trip_')
245
+ try:
246
+ path = await _save_video(video_file, tmp)
247
+ except Exception:
248
+ shutil.rmtree(tmp, ignore_errors=True)
249
+ raise
250
+ video = dict(path=path, trip_name=trip_name, video_name=video_file.filename)
251
+ try:
252
+ return _submit('upload', sens=sens, video=video, tmp=tmp)
253
+ except HTTPException:
254
+ if tmp:
255
+ shutil.rmtree(tmp, ignore_errors=True)
256
+ raise
257
+
258
+
259
+ @app.post('/api/demo')
260
+ def demo():
261
+ if not analyzer.ready:
262
+ raise HTTPException(503, 'Hệ thống chưa có model.')
263
+ if not analyzer.demo:
264
+ raise HTTPException(404, 'Máy chủ chưa có chuyến mẫu.')
265
+ return _submit('demo')
266
+
267
+
268
+ @app.get('/api/job/{jid}')
269
+ def job_status(jid: str):
270
+ job = JOBS.get(jid)
271
+ if job is None:
272
+ raise HTTPException(404, 'Không tìm thấy yêu cầu phân tích (có thể đã hết hạn). Hãy phân tích lại.')
273
+ out = dict(status=job['status'], progress=job.get('progress', ''))
274
+ if job['status'] == 'queued':
275
+ with LOCK:
276
+ out['queue_position'] = sum(1 for v in JOBS.values()
277
+ if v['status'] in ('queued', 'running') and v['created'] < job['created'])
278
+ elif job['status'] == 'done':
279
+ out['result'] = job['result']
280
+ elif job['status'] == 'error':
281
+ out['error'] = job.get('error')
282
+ return out
283
 
284
 
285
  if __name__ == '__main__':
286
+ # Space SDK Gradio khởi động bằng `python app.py` và chờ web ở cổng 7860.
 
287
  import uvicorn
288
 
289
+ # ZeroGPU chỉ "báo cáo khởi động" bên trong gr.Blocks.launch(); web này không gọi launch()
290
+ # nên gọi trực tiếp bước khởi động của spaces trước khi chạy uvicorn.
291
+ if spaces is not None:
292
+ try:
293
+ import spaces.zero as _zero
294
+ if hasattr(_zero, 'startup'):
295
+ _zero.startup()
296
+ except ImportError:
297
+ pass
298
 
299
  uvicorn.run(app, host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
dinov3_encoder.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Bản sao NGUYÊN VẸN của ../dust_dinov3/models/dinov3_video_encoder.py (video encoder DINOv3).
2
+ # Chép vào đây để thư mục web/ tự chạy được khi deploy. Không sửa file này.
3
+
4
+ """
5
+ DINOv3 Video Encoder - thay thế Video Swin Transformer 3D (models/video_swin_transformer.py)
6
+
7
+ Mặc định dùng bản DINOv3 NHỎ NHẤT: ViT-S/16 (timm: 'vit_small_patch16_dinov3.lvd1689m',
8
+ ~21.6M params, hidden_size = 384).
9
+
10
+ Interface giữ nguyên tương thích với SwinTransformer3D gốc:
11
+ - forward(x) -> logits [B, num_classes]
12
+ - get_vid_feature(x) -> feature vector [B, 1024]
13
+ - Input x shape (B, C, D, H, W) = (B, 3, 77, 224, 224)
14
+
15
+ Khác biệt so với Video Swin 3D gốc (chỉ ở phần encoder, pipeline giữ nguyên):
16
+ 1. Spatial: 3D W-MSA/SW-MSA -> DINOv3 ViT-S/16 chạy trên từng frame (frozen), lấy CLS token
17
+ 2. Temporal: 3D window attention + patch merging -> Temporal TransformerEncoder + CLS token
18
+ 3. Projection: Linear(384 -> 1024) để khớp chiều video feature 1024 của fusion head gốc
19
+ (models/SwinTransformer_fusion.py: Linear(num_features + 1024, num_classes))
20
+ """
21
+
22
+ import os
23
+ import torch
24
+ import torch.nn as nn
25
+ from torch.nn.init import trunc_normal_
26
+
27
+
28
+ DEFAULT_DINOV3_MODEL = 'vit_small_patch16_dinov3.lvd1689m'
29
+
30
+ # Ánh xạ tên timm -> Hugging Face model id (dùng cho nhánh fallback transformers).
31
+ # Lưu ý: repo facebook/dinov3-* trên Hugging Face là gated, cần đăng nhập + chấp nhận license.
32
+ TIMM_TO_HF = {
33
+ 'vit_small_patch16_dinov3': 'facebook/dinov3-vits16-pretrain-lvd1689m',
34
+ 'vit_small_plus_patch16_dinov3': 'facebook/dinov3-vits16plus-pretrain-lvd1689m',
35
+ 'vit_base_patch16_dinov3': 'facebook/dinov3-vitb16-pretrain-lvd1689m',
36
+ 'vit_large_patch16_dinov3': 'facebook/dinov3-vitl16-pretrain-lvd1689m',
37
+ }
38
+
39
+
40
+ def _hf_model_id(model_name):
41
+ base = model_name.split('.')[0]
42
+ return TIMM_TO_HF.get(base, model_name)
43
+
44
+
45
+ class DINOv3VideoEncoder(nn.Module):
46
+ """DINOv3-based Video Encoder thay thế Video Swin Transformer 3D.
47
+
48
+ Kiến trúc:
49
+ Video (B, C, D, H, W)
50
+ -> DINOv3 ViT-S/16 CLS token mỗi frame (B, D, 384)
51
+ -> + temporal pos-embed, prepend temporal CLS
52
+ -> Temporal TransformerEncoder (B, 1+D, 384)
53
+ -> temporal CLS -> LayerNorm -> Linear (B, 1024) = get_vid_feature
54
+ -> head (B, num_classes) = forward
55
+
56
+ Args:
57
+ num_classes (int): số class. Default 4 (giống project gốc).
58
+ num_frames (int): số frame video. Default 77.
59
+ model_name (str): tên DINOv3 trong timm (hoặc HF id). Default: ViT-S/16 (nhỏ nhất).
60
+ output_dim (int): chiều video feature. Default 1024 (khớp fusion head gốc).
61
+ temporal_layers (int): số tầng temporal encoder. Default 2.
62
+ temporal_heads (int|None): số head; None -> hidden_size // 64 (384 -> 6).
63
+ temporal_dropout (float): dropout temporal encoder. Default 0.1.
64
+ chunk_size (int): số frame đưa qua DINOv3 mỗi lần (tránh OOM). Default 16.
65
+ freeze_backbone (bool): đóng băng DINOv3. Default True.
66
+ pretrained (bool): tải trọng số pretrained DINOv3. Default True.
67
+ weights_path (str|None): file trọng số local (vd. model.safetensors tải từ
68
+ timm/vit_small_patch16_dinov3.lvd1689m). Nếu có và pretrained=True thì đọc
69
+ file này thay vì tải qua mạng. Chỉ áp dụng cho backend timm.
70
+ """
71
+
72
+ def __init__(self,
73
+ num_classes=4,
74
+ num_frames=77,
75
+ model_name=DEFAULT_DINOV3_MODEL,
76
+ output_dim=1024,
77
+ temporal_layers=2,
78
+ temporal_heads=None,
79
+ temporal_dropout=0.1,
80
+ chunk_size=16,
81
+ freeze_backbone=True,
82
+ pretrained=True,
83
+ weights_path=None):
84
+ super().__init__()
85
+
86
+ self.num_frames = num_frames
87
+ self.chunk_size = chunk_size
88
+ self.output_dim = output_dim
89
+ self.freeze_backbone = freeze_backbone
90
+ self.backend = None
91
+
92
+ # ----------------------------------------------------------------
93
+ # 1. DINOv3 backbone (thay patch embed + 4 stage của Swin 3D)
94
+ # Ưu tiên timm, fallback sang Hugging Face transformers.
95
+ # ----------------------------------------------------------------
96
+ if weights_path is not None and pretrained and not os.path.isfile(weights_path):
97
+ raise FileNotFoundError(f'Không tìm thấy file trọng số DINOv3: {weights_path}')
98
+
99
+ try:
100
+ import timm
101
+ extra = {}
102
+ if weights_path is not None and pretrained:
103
+ # Đọc trọng số từ file local thay vì tải từ Hugging Face Hub
104
+ extra['pretrained_cfg_overlay'] = dict(file=os.path.abspath(weights_path))
105
+ try:
106
+ # global_pool='token' -> output chính là CLS token (timm mặc định 'avg' cho DINOv3)
107
+ self.dino = timm.create_model(model_name, pretrained=pretrained,
108
+ num_classes=0, global_pool='token', **extra)
109
+ except TypeError:
110
+ self.dino = timm.create_model(model_name, pretrained=pretrained, num_classes=0, **extra)
111
+ self.hidden_size = self.dino.num_features
112
+ self.backend = 'timm'
113
+ except Exception as e_timm:
114
+ if weights_path is not None and pretrained:
115
+ # Không fallback sang HF: file local là trọng số định dạng timm
116
+ raise RuntimeError(f"Không load được '{weights_path}' vào timm model '{model_name}': {e_timm}")
117
+ hf_id = _hf_model_id(model_name)
118
+ try:
119
+ from transformers import AutoModel, AutoConfig
120
+ if pretrained:
121
+ self.dino = AutoModel.from_pretrained(hf_id)
122
+ else:
123
+ self.dino = AutoModel.from_config(AutoConfig.from_pretrained(hf_id))
124
+ self.hidden_size = self.dino.config.hidden_size
125
+ self.backend = 'transformers'
126
+ except Exception as e_hf:
127
+ raise RuntimeError(
128
+ f"Không thể khởi tạo DINOv3 '{model_name}' (HF id: '{hf_id}'). "
129
+ f"Lỗi timm: {e_timm}. Lỗi transformers: {e_hf}"
130
+ )
131
+
132
+ if freeze_backbone:
133
+ for param in self.dino.parameters():
134
+ param.requires_grad = False
135
+ self.dino.eval()
136
+
137
+ # ----------------------------------------------------------------
138
+ # 2. Temporal Transformer Encoder (thay vai trò temporal của 3D window attention)
139
+ # ----------------------------------------------------------------
140
+ if temporal_heads is None:
141
+ temporal_heads = max(1, self.hidden_size // 64) # 384 -> 6, 768 -> 12
142
+ if self.hidden_size % temporal_heads != 0:
143
+ raise ValueError(f'hidden_size={self.hidden_size} không chia hết cho temporal_heads={temporal_heads}')
144
+
145
+ self.temporal_pos_embed = nn.Parameter(torch.zeros(1, num_frames, self.hidden_size))
146
+ trunc_normal_(self.temporal_pos_embed, std=0.02)
147
+
148
+ self.temporal_cls = nn.Parameter(torch.zeros(1, 1, self.hidden_size))
149
+ trunc_normal_(self.temporal_cls, std=0.02)
150
+
151
+ encoder_layer = nn.TransformerEncoderLayer(
152
+ d_model=self.hidden_size,
153
+ nhead=temporal_heads,
154
+ dim_feedforward=self.hidden_size * 4,
155
+ dropout=temporal_dropout,
156
+ activation='gelu',
157
+ batch_first=True
158
+ )
159
+ self.temporal_encoder = nn.TransformerEncoder(encoder_layer, num_layers=temporal_layers)
160
+ self.temporal_norm = nn.LayerNorm(self.hidden_size)
161
+
162
+ # ----------------------------------------------------------------
163
+ # 3. Projection hidden_size -> output_dim (384 -> 1024)
164
+ # ----------------------------------------------------------------
165
+ self.proj = nn.Linear(self.hidden_size, output_dim)
166
+
167
+ # ----------------------------------------------------------------
168
+ # 4. Classification head (giống self.head của SwinTransformer3D)
169
+ # ----------------------------------------------------------------
170
+ self.head = nn.Linear(output_dim, num_classes) if num_classes > 0 else nn.Identity()
171
+
172
+ self._init_new_weights()
173
+
174
+ def _init_new_weights(self):
175
+ """Khởi tạo weights cho temporal encoder, projection, head (không đụng DINOv3)."""
176
+ for module in [self.temporal_encoder, self.temporal_norm, self.proj, self.head]:
177
+ for m in module.modules():
178
+ if isinstance(m, nn.Linear):
179
+ trunc_normal_(m.weight, std=0.02)
180
+ if m.bias is not None:
181
+ nn.init.constant_(m.bias, 0)
182
+ elif isinstance(m, nn.LayerNorm):
183
+ nn.init.constant_(m.bias, 0)
184
+ nn.init.constant_(m.weight, 1.0)
185
+
186
+ def _backbone_cls(self, chunk):
187
+ """CLS token của DINOv3 cho một chunk frame: (n, C, H, W) -> (n, hidden)."""
188
+ if self.backend == 'timm':
189
+ return self.dino(chunk)
190
+ outputs = self.dino(pixel_values=chunk)
191
+ return outputs.last_hidden_state[:, 0]
192
+
193
+ def _extract_frame_features(self, video):
194
+ """(B, C, D, H, W) -> (B, D, hidden): CLS token từng frame, xử lý theo chunk."""
195
+ B, C, D, H, W = video.shape
196
+ frames = video.permute(0, 2, 1, 3, 4).contiguous().reshape(B * D, C, H, W)
197
+
198
+ all_features = []
199
+ for i in range(0, B * D, self.chunk_size):
200
+ chunk = frames[i:i + self.chunk_size]
201
+ if self.freeze_backbone:
202
+ with torch.no_grad():
203
+ cls_tokens = self._backbone_cls(chunk)
204
+ else:
205
+ cls_tokens = self._backbone_cls(chunk)
206
+ all_features.append(cls_tokens)
207
+
208
+ frame_features = torch.cat(all_features, dim=0)
209
+ return frame_features.view(B, D, self.hidden_size)
210
+
211
+ def _temporal_aggregate(self, frame_features):
212
+ """(B, D, hidden) -> (B, output_dim)."""
213
+ B, D, _ = frame_features.shape
214
+ x = frame_features
215
+
216
+ if D <= self.num_frames:
217
+ x = x + self.temporal_pos_embed[:, :D]
218
+ else:
219
+ pos_emb = nn.functional.interpolate(
220
+ self.temporal_pos_embed.permute(0, 2, 1), size=D, mode='linear'
221
+ ).permute(0, 2, 1)
222
+ x = x + pos_emb
223
+
224
+ cls = self.temporal_cls.expand(B, -1, -1)
225
+ x = torch.cat([cls, x], dim=1) # (B, 1+D, hidden)
226
+ x = self.temporal_encoder(x)
227
+
228
+ video_feat = self.temporal_norm(x[:, 0]) # thay AdaptiveAvgPool3d + flatten
229
+ return self.proj(video_feat) # (B, 1024)
230
+
231
+ def get_vid_feature(self, x):
232
+ """Giống SwinTransformer3D.get_vid_feature(): (B, C, D, H, W) -> (B, 1024)."""
233
+ return self._temporal_aggregate(self._extract_frame_features(x))
234
+
235
+ def forward(self, x):
236
+ """Giống SwinTransformer3D.forward(): (B, C, D, H, W) -> (B, num_classes)."""
237
+ return self.head(self.get_vid_feature(x))
238
+
239
+ def train(self, mode=True):
240
+ """Giữ DINOv3 ở eval mode khi bị frozen."""
241
+ super().train(mode)
242
+ if self.freeze_backbone and hasattr(self, 'dino'):
243
+ self.dino.eval()
244
+ return self
inference.py CHANGED
@@ -1,5 +1,8 @@
1
  """
2
- Suy luận nhánh 1D (Stage 2 của DuST) cho một chuyến đi.
 
 
 
3
 
4
  Tiền xử lý PHẢI giống hệt lúc tạo dữ liệu train (dust_dinov3/prepare_uah_data.py):
5
  - làm sạch timestamp: bỏ phần sau lần quay ngược, bỏ cả nhóm dòng trùng timestamp,
@@ -7,24 +10,31 @@ Tiền xử lý PHẢI giống hệt lúc tạo dữ liệu train (dust_dinov3/p
7
  - cửa sổ = 51 mẫu RAW_ACCELEROMETERS liên tiếp, không chồng lấn, không nội suy;
8
  - loại cửa sổ có khoảng trống > 0.5 s, độ dài ngoài [4.6, 5.6] s, hoặc cờ kích hoạt != 1;
9
  - 3 kênh gia tốc đã lọc Kalman (cột 6-8), z-score bằng kine_norm_stats.json của tập train.
10
- Model: SwinTransformer_1D với đúng cấu hình trong step_fusion_1d.py.
11
  """
12
 
13
  import json
14
  import os
 
15
 
16
  import numpy as np
17
  import torch
18
 
 
 
19
  from swin1d import SwinTransformer_1D
 
20
 
21
  CLASSES = ['NORMAL', 'AGGRESSIVE', 'DROWSY']
 
22
  KINE_LEN = 51
23
  STRIDE_SEC = 5.0
24
  MAX_SAMPLE_GAP = 0.5
25
  MIN_SPAN, MAX_SPAN = 4.6, 5.6
26
- EVENT_MIN_PROB = 0.6 # cửa sổ bất thường có xác suất >= ngưỡng này mới được gom thành "đoạn cần xem lại"
27
- EVENT_HIGH_PROB = 0.8 # mức độ chắc chắn "Cao"
 
 
 
28
 
29
 
30
  class InputError(ValueError):
@@ -32,24 +42,45 @@ class InputError(ValueError):
32
 
33
 
34
  # ----------------------------------------------------------------------------
35
- # Đọc + làm sạch (giống prepare_uah_data.py)
36
  # ----------------------------------------------------------------------------
37
- def parse_table(text, expected_cols, name):
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  rows = []
39
  for ln, line in enumerate(text.splitlines(), 1):
40
  parts = line.split()
41
  if not parts:
42
  continue
43
  if len(parts) != expected_cols:
44
- raise InputError(f'{name}: dòng {ln} có {len(parts)} cột, cần {expected_cols} cột. '
45
- f'Hãy kiểm tra lại đúng loại file chưa.')
 
 
 
 
46
  try:
47
  rows.append([float(x) for x in parts])
48
  except ValueError:
49
  raise InputError(f'{name}: dòng {ln} có giá trị không phải số.')
50
  if len(rows) < KINE_LEN:
51
  raise InputError(f'{name}: quá ít dữ liệu ({len(rows)} dòng).')
52
- return np.asarray(rows, dtype=np.float64)
 
 
 
 
53
 
54
 
55
  def clean_timeseries(a):
@@ -82,9 +113,7 @@ def make_windows(acc, ambiguous):
82
  ts = seg[:, 0]
83
  span = ts[-1] - ts[0]
84
  reason = None
85
- if np.diff(ts).max() > MAX_SAMPLE_GAP:
86
- reason = 'mất dữ liệu cảm biến'
87
- elif not (MIN_SPAN <= span <= MAX_SPAN):
88
  reason = 'mất dữ liệu cảm biến'
89
  elif (seg[:, 1] != 1).any():
90
  reason = 'cảm biến chưa sẵn sàng'
@@ -98,90 +127,244 @@ def make_windows(acc, ambiguous):
98
  return out
99
 
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  # ----------------------------------------------------------------------------
102
  # Model
103
  # ----------------------------------------------------------------------------
 
 
 
 
 
104
  class Analyzer:
105
- def __init__(self, weights_dir):
106
- self.weights_dir = weights_dir
107
- self.model = None
108
- self.mean = self.std = None
109
  self.error = None
110
- w = os.path.join(weights_dir, 'final_1d.pth')
111
- s = os.path.join(weights_dir, 'kine_norm_stats.json')
112
- if not (os.path.isfile(w) and os.path.isfile(s)):
113
- self.error = f'Chưa có model: cần {w} và {s}'
 
114
  return
115
- stats = json.load(open(s))
116
  self.mean = np.asarray(stats['mean'], dtype=np.float32)[:, None]
117
  self.std = np.asarray(stats['std'], dtype=np.float32)[:, None]
118
- # Đúng cấu hình model trong dust_dinov3/step_fusion_1d.py
119
- m = SwinTransformer_1D(seq_len=KINE_LEN, in_chans=3, num_classes=4, window_size=8, drop_path_rate=0.1,
120
- patch_size=1, num_heads=[16, 16, 16, 16], depths=[2, 2, 6, 2], embed_dim=256)
121
- m.load_state_dict(torch.load(w, map_location='cpu'))
122
- m.eval()
123
- self.model = m
 
 
 
 
 
 
 
 
 
 
 
124
 
125
  @property
126
  def ready(self):
127
- return self.model is not None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
  @torch.no_grad()
130
- def predict(self, x):
131
- """x: (N, 3, 51) đã chuẩn hoá -> xác suất (N, 3) cho NORMAL/AGGRESSIVE/DROWSY.
132
- Model có 4 đầu ra như bản gốc (lớp 3 không dùng khi train) -> softmax trên 3 lớp thật."""
133
- probs = []
134
- for i in range(0, len(x), 64):
135
- logits = self.model(torch.from_numpy(x[i:i + 64]))[:, :3]
136
- probs.append(torch.softmax(logits, dim=1).numpy())
137
- return np.concatenate(probs) if probs else np.zeros((0, 3), np.float32)
138
-
139
- def analyze(self, acc_text, gps_text=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  if not self.ready:
141
  raise RuntimeError(self.error)
142
- acc, acc_info = clean_timeseries(parse_table(acc_text, 11, 'File cảm biến chuyển động'))
143
- gps, gps_info = (None, None)
144
- if gps_text:
145
- gps, gps_info = clean_timeseries(parse_table(gps_text, 12, 'File GPS'))
146
- ambiguous = [acc_info['ambiguous'], gps_info['ambiguous'] if gps_info else None]
147
-
148
- windows = make_windows(acc, ambiguous)
149
- valid = [w for w in windows if w['valid']]
150
- if not valid:
151
- raise InputError('Không có đoạn dữ liệu nào đủ chất lượng để phân tích.')
152
- x = np.stack([acc[w['i0']:w['i0'] + KINE_LEN, 5:8].T for w in valid]).astype(np.float32)
153
- x = (x - self.mean) / self.std
154
- probs = self.predict(x)
155
- for w, p in zip(valid, probs):
156
- w['probs'] = [round(float(v), 4) for v in p]
157
- w['label'] = CLASSES[int(np.argmax(p))]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
  return dict(
160
- trip=trip_summary(acc, gps, windows, valid, probs),
161
- windows=[{k: v for k, v in w.items() if k != 'i0'} for w in windows],
162
- events=find_events(windows),
163
- series=make_series(acc, gps),
164
- cleaning=dict(acc=acc_info, gps=gps_info),
 
 
 
165
  )
166
 
167
 
 
 
 
 
168
  # ----------------------------------------------------------------------------
169
  # Tổng hợp kết quả cho giao diện
170
  # ----------------------------------------------------------------------------
171
- def trip_summary(acc, gps, windows, valid, probs):
172
- dur = {c: 0.0 for c in CLASSES}
173
- for w in valid:
174
- dur[w['label']] += w['t_end'] - w['t_start']
175
- analysed = sum(dur.values())
176
- res = dict(
177
- start=float(acc[0, 0]), end=float(acc[-1, 0]), duration=float(acc[-1, 0] - acc[0, 0]),
178
- windows_total=len(windows), windows_valid=len(valid),
179
- analysed_seconds=analysed, seconds=dur,
180
- share={c: (dur[c] / analysed if analysed else 0.0) for c in CLASSES},
181
- # Đánh giá cả chuyến = lớp có xác suất trung bình cao nhất trên mọi cửa sổ hợp lệ
182
- trip_probs={c: float(probs[:, i].mean()) for i, c in enumerate(CLASSES)},
183
- )
184
- res['trip_label'] = max(res['trip_probs'], key=res['trip_probs'].get)
185
  if gps is not None and len(gps) > 1:
186
  v = gps[:, 1] / 3.6
187
  res['distance_km'] = float(np.sum((v[1:] + v[:-1]) / 2 * np.diff(gps[:, 0])) / 1000)
@@ -189,22 +372,37 @@ def trip_summary(acc, gps, windows, valid, probs):
189
  return res
190
 
191
 
192
- def find_events(windows):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  """Gom các cửa sổ liền nhau cùng nhãn bất thường (xác suất >= EVENT_MIN_PROB) thành một đoạn."""
194
  events, cur = [], None
195
  for w in windows:
196
- lab = w.get('label')
197
- p = max(w['probs']) if w['valid'] else 0.0
198
- hit = w['valid'] and lab != 'NORMAL' and p >= EVENT_MIN_PROB
199
- if hit and cur and cur['label'] == lab and w['t_start'] - cur['t_end'] <= STRIDE_SEC + 1.0:
200
  cur['t_end'] = w['t_end']
201
- cur['probs'].append(p)
202
  continue
203
  if cur:
204
  events.append(cur)
205
  cur = None
206
  if hit:
207
- cur = dict(label=lab, t_start=w['t_start'], t_end=w['t_end'], probs=[p])
208
  if cur:
209
  events.append(cur)
210
  for e in events:
 
1
  """
2
+ Suy luận DuST-DINOv3 cho một chuyến đi, gồm 3 model:
3
+ - sensor : 1D Swin (Stage 2) trên 3 kênh gia tốc
4
+ - video : DINOv3 + Temporal Transformer (Stage 1) trên 77 frame mỗi đoạn
5
+ - fusion : 1D Swin fusion (Stage 4) trên gia tốc + vector video 1024 chiều
6
 
7
  Tiền xử lý PHẢI giống hệt lúc tạo dữ liệu train (dust_dinov3/prepare_uah_data.py):
8
  - làm sạch timestamp: bỏ phần sau lần quay ngược, bỏ cả nhóm dòng trùng timestamp,
 
10
  - cửa sổ = 51 mẫu RAW_ACCELEROMETERS liên tiếp, không chồng lấn, không nội suy;
11
  - loại cửa sổ có khoảng trống > 0.5 s, độ dài ngoài [4.6, 5.6] s, hoặc cờ kích hoạt != 1;
12
  - 3 kênh gia tốc đã lọc Kalman (cột 6-8), z-score bằng kine_norm_stats.json của tập train.
 
13
  """
14
 
15
  import json
16
  import os
17
+ import tempfile
18
 
19
  import numpy as np
20
  import torch
21
 
22
+ import video_pipeline as vp
23
+ from dinov3_encoder import DINOv3VideoEncoder
24
  from swin1d import SwinTransformer_1D
25
+ from swin_fusion import SwinTransformer_1D as SwinTransformer_1D_fusion
26
 
27
  CLASSES = ['NORMAL', 'AGGRESSIVE', 'DROWSY']
28
+ MODELS = ['sensor', 'video', 'fusion']
29
  KINE_LEN = 51
30
  STRIDE_SEC = 5.0
31
  MAX_SAMPLE_GAP = 0.5
32
  MIN_SPAN, MAX_SPAN = 4.6, 5.6
33
+ MIN_TRIP_SEC = 60 # chuyến ngắn hơn 1 phút: từ chối
34
+ MAX_TRIP_SEC = 2 * 3600 # chuyến dài hơn 2 giờ: từ chối (bảo vệ máy chủ)
35
+ EVENT_MIN_PROB = 0.6 # cửa sổ bất thường có xác suất >= ngưỡng này mới được gom thành "đoạn cần xem lại"
36
+ EVENT_HIGH_PROB = 0.8 # mức độ chắc chắn "Cao"
37
+ VIDEO_CPU_MAX_WINDOWS = int(os.environ.get('VIDEO_CPU_MAX_WINDOWS', 24)) # giới hạn số đoạn video khi chạy CPU
38
 
39
 
40
  class InputError(ValueError):
 
42
 
43
 
44
  # ----------------------------------------------------------------------------
45
+ # Đọc + kiểm tra file
46
  # ----------------------------------------------------------------------------
47
+ def decode_text(data, name):
48
+ if not data or not data.strip():
49
+ raise InputError(f'{name} trống.')
50
+ if b'\x00' in data[:8192]:
51
+ raise InputError(f'{name} không phải file văn bản (có thể là file nhị phân hoặc video).')
52
+ for enc in ('utf-8-sig', 'utf-8'):
53
+ try:
54
+ return data.decode(enc)
55
+ except UnicodeDecodeError:
56
+ pass
57
+ raise InputError(f'{name} không đọc được (sai mã hoá ký tự).')
58
+
59
+
60
+ def parse_table(text, expected_cols, name, swapped_hint=None):
61
  rows = []
62
  for ln, line in enumerate(text.splitlines(), 1):
63
  parts = line.split()
64
  if not parts:
65
  continue
66
  if len(parts) != expected_cols:
67
+ hint = ''
68
+ if swapped_hint and len(parts) == swapped_hint[0]:
69
+ hint = ' ' + swapped_hint[1]
70
+ elif ',' in line or ';' in line:
71
+ hint = ' Các cột phải cách nhau bằng khoảng trắng (định dạng UAH-DriveSet), không dùng dấu phẩy.'
72
+ raise InputError(f'{name}: dòng {ln} có {len(parts)} cột, cần {expected_cols} cột.{hint}')
73
  try:
74
  rows.append([float(x) for x in parts])
75
  except ValueError:
76
  raise InputError(f'{name}: dòng {ln} có giá trị không phải số.')
77
  if len(rows) < KINE_LEN:
78
  raise InputError(f'{name}: quá ít dữ liệu ({len(rows)} dòng).')
79
+ a = np.asarray(rows, dtype=np.float64)
80
+ bad = np.where(~np.isfinite(a).all(axis=1))[0]
81
+ if len(bad):
82
+ raise InputError(f'{name}: dòng {bad[0] + 1} có giá trị không hợp lệ (NaN hoặc vô cực).')
83
+ return a
84
 
85
 
86
  def clean_timeseries(a):
 
113
  ts = seg[:, 0]
114
  span = ts[-1] - ts[0]
115
  reason = None
116
+ if np.diff(ts).max() > MAX_SAMPLE_GAP or not (MIN_SPAN <= span <= MAX_SPAN):
 
 
117
  reason = 'mất dữ liệu cảm biến'
118
  elif (seg[:, 1] != 1).any():
119
  reason = 'cảm biến chưa sẵn sàng'
 
127
  return out
128
 
129
 
130
+ def load_sensors(acc_bytes, gps_bytes=None):
131
+ """Kiểm tra + làm sạch file cảm biến (nhanh, chạy ngay khi upload). Ném InputError nếu không hợp lệ."""
132
+ acc_text = decode_text(acc_bytes, 'File cảm biến chuyển động')
133
+ acc, acc_info = clean_timeseries(parse_table(
134
+ acc_text, 11, 'File cảm biến chuyển động',
135
+ swapped_hint=(12, 'Có vẻ đây là file GPS. Hãy chọn RAW_ACCELEROMETERS.txt.')))
136
+ gps, gps_info = None, None
137
+ if gps_bytes:
138
+ gps_text = decode_text(gps_bytes, 'File GPS')
139
+ gps, gps_info = clean_timeseries(parse_table(
140
+ gps_text, 12, 'File GPS',
141
+ swapped_hint=(11, 'Có vẻ đây là file cảm biến chuyển động. Hãy chọn RAW_GPS.txt.')))
142
+ if len(acc) < KINE_LEN:
143
+ raise InputError('File cảm biến chuyển động: còn quá ít dữ liệu sau khi làm sạch.')
144
+ dur = float(acc[-1, 0] - acc[0, 0])
145
+ if dur < MIN_TRIP_SEC:
146
+ raise InputError(f'Chuyến đi quá ngắn ({dur:.0f} giây). Cần ít nhất {MIN_TRIP_SEC // 60} phút dữ liệu.')
147
+ if dur > MAX_TRIP_SEC:
148
+ raise InputError(f'Chuyến đi quá dài ({dur / 3600:.1f} giờ). Hệ thống chỉ nhận tối đa {MAX_TRIP_SEC // 3600} giờ.')
149
+ ambiguous = [acc_info['ambiguous'], gps_info['ambiguous'] if gps_info else None]
150
+ windows = make_windows(acc, ambiguous)
151
+ if not any(w['valid'] for w in windows):
152
+ raise InputError('Không có đoạn dữ liệu nào đủ chất lượng để phân tích (mất dữ liệu hoặc cảm biến chưa sẵn sàng).')
153
+ return dict(acc=acc, gps=gps, acc_info=acc_info, gps_info=gps_info, windows=windows)
154
+
155
+
156
  # ----------------------------------------------------------------------------
157
  # Model
158
  # ----------------------------------------------------------------------------
159
+ def _softmax3(logits):
160
+ """Model có 4 đầu ra như bản gốc (lớp 3 không dùng khi train) -> softmax trên 3 lớp thật."""
161
+ return torch.softmax(logits[:, :3].float(), dim=1).numpy()
162
+
163
+
164
  class Analyzer:
165
+ def __init__(self, weights_dir, demo_dir=None):
 
 
 
166
  self.error = None
167
+ self.model_1d = self.video = self.fusion = None
168
+ self.demo = None
169
+ w = lambda f: os.path.join(weights_dir, f)
170
+ if not (os.path.isfile(w('final_1d.pth')) and os.path.isfile(w('kine_norm_stats.json'))):
171
+ self.error = f'Chưa có model: cần {w("final_1d.pth")} và {w("kine_norm_stats.json")}'
172
  return
173
+ stats = json.load(open(w('kine_norm_stats.json')))
174
  self.mean = np.asarray(stats['mean'], dtype=np.float32)[:, None]
175
  self.std = np.asarray(stats['std'], dtype=np.float32)[:, None]
176
+ # Cấu hình giống dust_dinov3/step_fusion_1d.py và step_fusion.py
177
+ cfg = dict(seq_len=KINE_LEN, in_chans=3, num_classes=4, window_size=8, patch_size=1,
178
+ num_heads=[16, 16, 16, 16], depths=[2, 2, 6, 2], embed_dim=256)
179
+ self.model_1d = SwinTransformer_1D(drop_path_rate=0.1, **cfg)
180
+ self.model_1d.load_state_dict(torch.load(w('final_1d.pth'), map_location='cpu'))
181
+ self.model_1d.eval()
182
+ if os.path.isfile(w('video_3d.pth')):
183
+ self.video = DINOv3VideoEncoder(num_classes=4, num_frames=vp.NUM_FRAMES, output_dim=1024,
184
+ freeze_backbone=True, pretrained=False)
185
+ self.video.load_state_dict(torch.load(w('video_3d.pth'), map_location='cpu'))
186
+ self.video.eval()
187
+ if self.video is not None and os.path.isfile(w('fusion.pth')):
188
+ self.fusion = SwinTransformer_1D_fusion(**cfg)
189
+ self.fusion.load_state_dict(torch.load(w('fusion.pth'), map_location='cpu'))
190
+ self.fusion.eval()
191
+ if demo_dir and os.path.isfile(os.path.join(demo_dir, 'meta.json')):
192
+ self.demo = dict(dir=demo_dir, meta=json.load(open(os.path.join(demo_dir, 'meta.json'), encoding='utf-8')))
193
 
194
  @property
195
  def ready(self):
196
+ return self.model_1d is not None
197
+
198
+ def status(self):
199
+ return dict(ready=self.ready, video=self.video is not None, fusion=self.fusion is not None,
200
+ demo=self.demo['meta'] if self.demo else None, message=self.error or 'Sẵn sàng')
201
+
202
+ def demo_sensors(self):
203
+ d = self.demo['dir']
204
+ acc = open(os.path.join(d, 'RAW_ACCELEROMETERS.txt'), 'rb').read()
205
+ gps_p = os.path.join(d, 'RAW_GPS.txt')
206
+ gps = open(gps_p, 'rb').read() if os.path.isfile(gps_p) else None
207
+ return load_sensors(acc, gps)
208
+
209
+ # ---- tiện ích
210
+ def _kine(self, sens, idx):
211
+ acc, wins = sens['acc'], sens['windows']
212
+ x = np.stack([acc[wins[i]['i0']:wins[i]['i0'] + KINE_LEN, 5:8].T for i in idx]).astype(np.float32)
213
+ return (x - self.mean) / self.std
214
 
215
  @torch.no_grad()
216
+ def _predict_1d(self, x):
217
+ out = [_softmax3(self.model_1d(torch.from_numpy(x[i:i + 64]))) for i in range(0, len(x), 64)]
218
+ return np.concatenate(out)
219
+
220
+ @torch.no_grad()
221
+ def _video_and_fusion(self, cls, kine):
222
+ """cls: (N, 77, 384) CLS token DINOv3; kine: (N, 3, 51) đã chuẩn hoá."""
223
+ pv, pf = [], []
224
+ for i in range(0, len(cls), 32):
225
+ feat = self.video._temporal_aggregate(torch.from_numpy(cls[i:i + 32].astype(np.float32)))
226
+ pv.append(_softmax3(self.video.head(feat)))
227
+ if self.fusion is not None:
228
+ pf.append(_softmax3(self.fusion(torch.from_numpy(kine[i:i + 32]), feat)))
229
+ return np.concatenate(pv), (np.concatenate(pf) if pf else None)
230
+
231
+ # ---- nhánh video
232
+ def _video_branch(self, sens, video, progress, gpu_fn):
233
+ """Trả về (cls theo chỉ số cửa sổ, thumbs theo chỉ số cửa sổ, thông tin video)."""
234
+ acc, gps, wins = sens['acc'], sens['gps'], sens['windows']
235
+ info = dict(status='none', message='')
236
+ path = video['path']
237
+ progress('Đang đồng bộ video với dữ liệu cảm biến…')
238
+ fps, frame_times, flow_t, flow_x = vp.scan_video(path, progress)
239
+ base = vp.name_offset(video.get('trip_name'), video.get('video_name'))
240
+ sync = vp.verify_offset(base, flow_t, flow_x, acc, gps)
241
+ info.update(sync=dict((k, v) for k, v in sync.items() if k != 'reason'))
242
+ if not sync['verified']:
243
+ info.update(status='sync_failed',
244
+ message=f'Không đồng bộ được video với cảm biến ({sync.get("reason")}). '
245
+ f'Chỉ hiện kết quả từ dữ liệu cảm biến.')
246
+ return {}, {}, info
247
+ offset = sync['offset']
248
+ plans = vp.plan_frames(wins, acc, offset, frame_times, fps)
249
+ if not plans:
250
+ info.update(status='no_overlap', message='Video không trùng thời gian với đoạn dữ liệu cảm biến nào.')
251
+ return {}, {}, info
252
+ with tempfile.TemporaryDirectory() as tmp:
253
+ fpath = os.path.join(tmp, 'frames.npy')
254
+ progress('Đang lấy frame video…')
255
+ complete, thumbs = vp.extract_frames(path, plans, fpath, progress)
256
+ rows = [i for i, ok in enumerate(complete) if ok]
257
+ device = 'cpu'
258
+ cls = None
259
+ if gpu_fn is not None:
260
+ try:
261
+ progress(f'Đang chạy DINOv3 trên GPU cho {len(rows)} đoạn…')
262
+ cls = gpu_fn(fpath, rows)
263
+ device = 'gpu'
264
+ except Exception as e: # hết hạn mức ZeroGPU, lỗi GPU... -> chạy CPU
265
+ info['gpu_error'] = str(e)[:300]
266
+ if cls is None:
267
+ total = len(rows)
268
+ if len(rows) > VIDEO_CPU_MAX_WINDOWS:
269
+ pick = np.unique(np.round(np.linspace(0, len(rows) - 1, VIDEO_CPU_MAX_WINDOWS)).astype(int))
270
+ rows = [rows[i] for i in pick]
271
+ progress(f'Đang chạy DINOv3 trên CPU cho {len(rows)} đoạn…')
272
+ cls = vp.backbone_cls(self.video, fpath, rows, device='cpu', progress=progress)
273
+ if len(rows) < total:
274
+ info.update(status='cpu_limited',
275
+ message=f'Không có GPU nên chỉ phân tích video {len(rows)}/{total} đoạn, '
276
+ f'trải đều trong chuyến. Các đoạn còn lại chỉ có kết quả cảm biến.')
277
+ cls_by_win = {plans[r][0]: cls[k] for k, r in enumerate(rows)}
278
+ thumb_by_win = {plans[pi][0]: thumbs[pi] for pi in range(len(plans)) if thumbs[pi]}
279
+ if info['status'] == 'none':
280
+ info['status'] = 'ok'
281
+ info.update(offset=offset, device=device, windows_analysed=len(cls_by_win), windows_possible=len(plans))
282
+ return cls_by_win, thumb_by_win, info
283
+
284
+ def _demo_branch(self, sens):
285
+ d = self.demo['dir']
286
+ z = np.load(os.path.join(d, 'cache.npz'))
287
+ thumbs = json.load(open(os.path.join(d, 'thumbs.json'), encoding='utf-8'))
288
+ key = {round(float(t), 2): k for k, t in enumerate(z['t_start'])}
289
+ cls_by_win, thumb_by_win = {}, {}
290
+ for wi, w in enumerate(sens['windows']):
291
+ k = key.get(round(w['t_start'], 2))
292
+ if k is not None and w['valid']:
293
+ cls_by_win[wi] = z['cls'][k]
294
+ if thumbs[k]:
295
+ thumb_by_win[wi] = thumbs[k]
296
+ meta = self.demo['meta']
297
+ info = dict(status='ok', device='tính sẵn (chuyến mẫu)', offset=meta.get('offset'), sync=meta.get('sync'),
298
+ windows_analysed=len(cls_by_win), windows_possible=len(cls_by_win),
299
+ message='Đặc trưng DINOv3 của chuyến mẫu được tính sẵn; Temporal Transformer, '
300
+ 'nhánh video và fusion chạy trực tiếp.')
301
+ return cls_by_win, thumb_by_win, info
302
+
303
+ # ---- toàn bộ
304
+ def analyze(self, sens, video=None, demo=False, progress=None, gpu_fn=None):
305
  if not self.ready:
306
  raise RuntimeError(self.error)
307
+ progress = progress or (lambda m: None)
308
+ wins = sens['windows']
309
+ valid_idx = [i for i, w in enumerate(wins) if w['valid']]
310
+
311
+ progress('Đang phân tích dữ liệu cảm biến…')
312
+ kine = self._kine(sens, valid_idx)
313
+ p1 = self._predict_1d(kine)
314
+ for i, p in zip(valid_idx, p1):
315
+ wins[i]['sensor'] = _pack(p)
316
+
317
+ cls_by_win, thumb_by_win = {}, {}
318
+ vinfo = dict(status='none', message='Không có video. Chỉ phân tích dữ liệu cảm biến.')
319
+ if self.video is not None and (demo or video):
320
+ if demo:
321
+ cls_by_win, thumb_by_win, vinfo = self._demo_branch(sens)
322
+ else:
323
+ cls_by_win, thumb_by_win, vinfo = self._video_branch(sens, video, progress, gpu_fn)
324
+ elif video and self.video is None:
325
+ vinfo = dict(status='none', message='Máy chủ chưa có model video. Chỉ phân tích dữ liệu cảm biến.')
326
+
327
+ if cls_by_win:
328
+ progress('Đang chạy nhánh video và fusion…')
329
+ vidx = sorted(cls_by_win)
330
+ cls = np.stack([cls_by_win[i] for i in vidx])
331
+ pv, pf = self._video_and_fusion(cls, self._kine(sens, vidx))
332
+ for k, i in enumerate(vidx):
333
+ wins[i]['video'] = _pack(pv[k])
334
+ if pf is not None:
335
+ wins[i]['fusion'] = _pack(pf[k])
336
+
337
+ thumbs, out_w = [], []
338
+ for i, w in enumerate(wins):
339
+ ow = {k: w.get(k) for k in ('t_start', 't_end', 'valid', 'reason', 'sensor', 'video', 'fusion')}
340
+ if i in thumb_by_win:
341
+ ow['thumb'] = len(thumbs)
342
+ thumbs.append(thumb_by_win[i])
343
+ out_w.append(ow)
344
 
345
  return dict(
346
+ demo=bool(demo),
347
+ trip=trip_info(sens),
348
+ models={m: summarize(out_w, m) for m in MODELS},
349
+ windows=out_w,
350
+ thumbs=thumbs,
351
+ video=vinfo,
352
+ series=make_series(sens['acc'], sens['gps']),
353
+ cleaning=dict(acc=sens['acc_info'], gps=sens['gps_info']),
354
  )
355
 
356
 
357
+ def _pack(p):
358
+ return dict(probs=[round(float(v), 4) for v in p], label=CLASSES[int(np.argmax(p))])
359
+
360
+
361
  # ----------------------------------------------------------------------------
362
  # Tổng hợp kết quả cho giao diện
363
  # ----------------------------------------------------------------------------
364
+ def trip_info(sens):
365
+ acc, gps, wins = sens['acc'], sens['gps'], sens['windows']
366
+ res = dict(start=float(acc[0, 0]), end=float(acc[-1, 0]), duration=float(acc[-1, 0] - acc[0, 0]),
367
+ windows_total=len(wins), windows_valid=sum(w['valid'] for w in wins))
 
 
 
 
 
 
 
 
 
 
368
  if gps is not None and len(gps) > 1:
369
  v = gps[:, 1] / 3.6
370
  res['distance_km'] = float(np.sum((v[1:] + v[:-1]) / 2 * np.diff(gps[:, 0])) / 1000)
 
372
  return res
373
 
374
 
375
+ def summarize(windows, key):
376
+ have = [w for w in windows if w.get(key)]
377
+ if not have:
378
+ return None
379
+ dur = {c: 0.0 for c in CLASSES}
380
+ for w in have:
381
+ dur[w[key]['label']] += w['t_end'] - w['t_start']
382
+ analysed = sum(dur.values())
383
+ probs = np.array([w[key]['probs'] for w in have])
384
+ trip_probs = {c: float(probs[:, i].mean()) for i, c in enumerate(CLASSES)}
385
+ return dict(windows=len(have), analysed_seconds=analysed, seconds=dur,
386
+ share={c: (dur[c] / analysed if analysed else 0.0) for c in CLASSES},
387
+ trip_probs=trip_probs, trip_label=max(trip_probs, key=trip_probs.get),
388
+ events=find_events(windows, key))
389
+
390
+
391
+ def find_events(windows, key):
392
  """Gom các cửa sổ liền nhau cùng nhãn bất thường (xác suất >= EVENT_MIN_PROB) thành một đoạn."""
393
  events, cur = [], None
394
  for w in windows:
395
+ r = w.get(key)
396
+ hit = bool(r) and r['label'] != 'NORMAL' and max(r['probs']) >= EVENT_MIN_PROB
397
+ if hit and cur and cur['label'] == r['label'] and w['t_start'] - cur['t_end'] <= STRIDE_SEC + 1.0:
 
398
  cur['t_end'] = w['t_end']
399
+ cur['probs'].append(max(r['probs']))
400
  continue
401
  if cur:
402
  events.append(cur)
403
  cur = None
404
  if hit:
405
+ cur = dict(label=r['label'], t_start=w['t_start'], t_end=w['t_end'], probs=[max(r['probs'])])
406
  if cur:
407
  events.append(cur)
408
  for e in events:
requirements.txt CHANGED
@@ -1,7 +1,11 @@
1
  --extra-index-url https://download.pytorch.org/whl/cpu
2
  torch==2.12.1
3
  numpy
 
 
4
  # - torch 2.12.1: phiên bản nằm trong danh sách ZeroGPU hỗ trợ (2.12.0 bị từ chối).
5
  # - numpy không ghim: Space ZeroGPU chạy Python 3.10, numpy >= 2.3 cần Python 3.11 nên để pip tự chọn bản hợp.
6
- # - fastapi, uvicorn, python-multipart: Space SDK Gradio đã cài sẵn kèm gradio, không ghim riêng để tránh xung đột.
7
- # Chạy trên máy (không có gradio) thì cài thêm: pip install fastapi uvicorn python-multipart
 
 
 
1
  --extra-index-url https://download.pytorch.org/whl/cpu
2
  torch==2.12.1
3
  numpy
4
+ timm==1.0.27
5
+ opencv-python-headless==4.13.0.92
6
  # - torch 2.12.1: phiên bản nằm trong danh sách ZeroGPU hỗ trợ (2.12.0 bị từ chối).
7
  # - numpy không ghim: Space ZeroGPU chạy Python 3.10, numpy >= 2.3 cần Python 3.11 nên để pip tự chọn bản hợp.
8
+ # - timm: tạo kiến trúc DINOv3 ViT-S/16 cho nhánh video (trọng số lấy từ weights/video_3d.pth, không tải mạng).
9
+ # - opencv-python-headless: đọc video, optical flow để đồng bộ, cắt frame.
10
+ # - fastapi, uvicorn, python-multipart, huggingface_hub: Space SDK Gradio đã cài sẵn kèm gradio.
11
+ # Chạy trên máy (không có gradio) thì cài thêm: pip install fastapi uvicorn python-multipart huggingface_hub
static/index.html CHANGED
@@ -7,7 +7,7 @@
7
  <style>
8
  :root {
9
  --bg: #0b1120; --panel: #111827; --line: #1f2937; --soft: #1e293b; --muted: #94a3b8; --text: #f1f5f9;
10
- --normal: #22c55e; --aggr: #ef4444; --drowsy: #eab308; --invalid: #475569; --accent: #2563eb;
11
  }
12
  * { box-sizing: border-box; margin: 0; padding: 0; }
13
  body { background: #020617; color: var(--text); font-family: 'Segoe UI', Roboto, Arial, sans-serif; font-size: 14px; padding: 12px; }
@@ -25,7 +25,7 @@
25
  .dot.ok { background: var(--normal); box-shadow: 0 0 8px var(--normal); }
26
  .dot.bad { background: var(--aggr); }
27
 
28
- .grid { display: grid; grid-template-columns: 330px minmax(0, 1fr) 430px; gap: 12px; align-items: start; }
29
  @media (max-width: 1250px) { .grid { grid-template-columns: 1fr; } }
30
  .col { display: flex; flex-direction: column; gap: 12px; min-width: 0; }
31
  .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; }
@@ -34,6 +34,8 @@
34
  .ph small { text-transform: none; font-weight: 600; color: var(--muted); font-size: 12px; }
35
  .hint { font-size: 12.5px; color: var(--muted); line-height: 1.45; }
36
 
 
 
37
  label.f { display: block; font-size: 12.5px; color: var(--muted); margin: 8px 0 4px; }
38
  input[type=text] { width: 100%; background: var(--soft); border: 1px solid #334155; color: var(--text);
39
  border-radius: 6px; padding: 7px 9px; font-size: 14px; }
@@ -42,7 +44,7 @@
42
  text-align: center; cursor: pointer; font-size: 13.5px; font-weight: 600; color: #93c5fd; margin-top: 8px; }
43
  .pick input { display: none; }
44
  .files { font-size: 12.5px; margin-top: 6px; line-height: 1.6; }
45
- .files .ok { color: #4ade80; } .files .miss { color: var(--muted); }
46
  details { margin-top: 8px; font-size: 12.5px; color: var(--muted); }
47
  details summary { cursor: pointer; color: #93c5fd; }
48
  .btn { display: block; width: 100%; border: 0; border-radius: 7px; padding: 10px; font-size: 14.5px; font-weight: 700;
@@ -53,6 +55,18 @@
53
  .btn-sm.on { background: var(--accent); border-color: #3b82f6; color: #fff; }
54
  .err { background: rgba(239,68,68,.12); border: 1px solid var(--aggr); color: #fca5a5; border-radius: 7px;
55
  padding: 8px 10px; font-size: 13px; margin-top: 10px; }
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  .info { display: grid; grid-template-columns: 1fr 1fr; gap: 10px 8px; }
58
  .info label { display: block; font-size: 12px; color: #64748b; }
@@ -66,23 +80,32 @@
66
  .bar-bg { height: 9px; background: var(--soft); border-radius: 5px; overflow: hidden; }
67
  .bar-fg { height: 100%; }
68
  .note { margin-top: 10px; font-size: 12px; color: var(--muted); border-top: 1px solid var(--line); padding-top: 8px; line-height: 1.45; }
69
-
70
- .video-box { height: 190px; border-radius: 8px; border: 1px dashed #334155; background: #020617; display: flex;
71
- flex-direction: column; align-items: center; justify-content: center; gap: 6px; text-align: center; padding: 16px; }
72
- .video-box .big { font-size: 30px; }
 
 
 
 
 
 
 
 
 
73
 
74
  .timeline { position: relative; height: 26px; border-radius: 6px; overflow: hidden; background: var(--soft);
75
  border: 1px solid #334155; margin: 4px 0 6px; cursor: pointer; }
76
- .timeline div.seg { position: absolute; top: 0; bottom: 0; }
77
  .timeline .cursor { position: absolute; top: -2px; bottom: -2px; border: 2px solid #fff; border-radius: 3px;
78
  box-shadow: 0 0 6px #fff; pointer-events: none; }
79
  .ticks { display: flex; justify-content: space-between; font-size: 12px; color: var(--muted); }
80
  .legend { display: flex; gap: 14px; flex-wrap: wrap; font-size: 12.5px; margin-top: 8px; }
81
  .legend i { display: inline-block; width: 11px; height: 11px; border-radius: 3px; margin-right: 5px; vertical-align: -1px; }
82
 
83
- table { width: 100%; border-collapse: collapse; font-size: 13.5px; }
84
- th { text-align: left; color: #64748b; font-size: 12px; padding: 6px 6px; border-bottom: 1px solid var(--line); text-transform: uppercase; }
85
- td { padding: 8px 6px; border-bottom: 1px solid var(--soft); vertical-align: middle; }
86
  tr.sel { background: rgba(37,99,235,.14); }
87
  .lvl { border-radius: 10px; padding: 2px 8px; font-size: 12px; font-weight: 700; white-space: nowrap; border: 1px solid; }
88
  .lvl.high { color: #f87171; border-color: var(--aggr); background: rgba(239,68,68,.15); }
@@ -116,8 +139,15 @@
116
  <div class="grid">
117
  <!-- ================= CỘT TRÁI ================= -->
118
  <div class="col">
 
 
 
 
 
 
 
119
  <div class="panel">
120
- <div class="ph"><span>1. Chọn chuyến đi</span></div>
121
  <div class="row2">
122
  <div><label class="f">Mã tài xế</label><input type="text" id="driver" placeholder="VD: TX-0123"></div>
123
  <div><label class="f">Biển số xe</label><input type="text" id="plate" placeholder="VD: 30A-123.45"></div>
@@ -125,18 +155,23 @@
125
  <label class="pick">📁 Chọn thư mục chuyến đi
126
  <input type="file" id="pickDir" webkitdirectory multiple>
127
  </label>
128
- <div class="files" id="fileList">
129
- <div class="miss" id="accState">• Dữ liệu cảm biến chuyển động: chưa có</div>
130
- <div class="miss" id="gpsState">• Dữ liệu GPS (không bắt buộc): chưa có</div>
 
131
  </div>
132
  <details>
133
  <summary>Hoặc chọn từng file</summary>
134
- <label class="f">File cảm biến chuyển động (RAW_ACCELEROMETERS.txt)</label>
135
- <input type="file" id="pickAcc" accept=".txt">
136
- <label class="f">File GPS (RAW_GPS.txt, không bắt buộc)</label>
137
- <input type="file" id="pickGps" accept=".txt">
 
 
138
  </details>
 
139
  <button class="btn" id="runBtn" disabled>Phân tích chuyến đi</button>
 
140
  <div class="err" id="errBox" hidden></div>
141
  </div>
142
 
@@ -155,17 +190,20 @@
155
  </div>
156
 
157
  <div class="panel" id="resultPanel" hidden>
158
- <div class="ph"><span>Kết luận</span></div>
159
  <div class="verdict">
160
  <div class="vbadge" id="vBadge"></div>
161
  <div class="vtext" id="vText"></div>
162
  </div>
163
  <div id="bars"></div>
 
 
164
  <details>
165
  <summary>Kết luận được tính thế nào?</summary>
166
- <p style="margin-top:6px; line-height:1.5">Chuyến đi được chia thành các đoạn 5 giây. AI xem dữ liệu cảm biến của từng đoạn và
167
- cho biết đoạn đó giống kiểu lái nào nhất. Nếu tổng thời gian lái hung hăng và buồn ngủ dưới 15% thì <b>Lái xe ổn định</b>,
168
- từ 15% đến dưới 40% thì <b>Cần chú ý</b>, từ 40% trở lên thì <b>Cần kiểm tra kỹ</b>.</p>
 
169
  </details>
170
  <div class="note">Kết quả do AI tạo ra, chỉ để tham khảo. Nhân viên cần xem lại các đoạn được đánh dấu trước khi kết luận về tài xế.</div>
171
  </div>
@@ -173,13 +211,23 @@
173
 
174
  <!-- ================= CỘT GIỮA ================= -->
175
  <div class="col">
 
 
 
 
 
 
 
 
 
176
  <div class="panel">
177
  <div class="ph"><span>Video hành trình</span><small id="videoTime"></small></div>
178
- <div class="video-box">
179
- <div class="big">🎥</div>
180
- <div style="font-weight:700">Sẽ có ở phiên bản sau</div>
181
- <div class="hint">Phiên bản sau sẽ phát video camera hành trình đúng thời điểm bạn chọn.<br>Bản hiện tại chỉ phân tích dữ liệu cảm biến chuyển động của xe.</div>
182
  </div>
 
 
183
  </div>
184
 
185
  <div class="panel">
@@ -193,6 +241,7 @@
193
  <span><i style="background:var(--aggr)"></i>Lái xe hung hăng</span>
194
  <span><i style="background:var(--drowsy)"></i>Dấu hiệu buồn ngủ</span>
195
  <span><i style="background:var(--invalid)"></i>Thiếu dữ liệu</span>
 
196
  </div>
197
  </div>
198
  </div>
@@ -200,7 +249,7 @@
200
  <div class="panel">
201
  <div class="ph"><span>Các đoạn cần xem lại</span><small id="evCount"></small></div>
202
  <div id="evEmpty" class="empty">Chưa có kết quả.</div>
203
- <table id="evTable" hidden>
204
  <thead><tr><th>Thời điểm</th><th>Hành vi</th><th>Kéo dài</th><th>AI chắc chắn</th><th></th></tr></thead>
205
  <tbody id="evBody"></tbody>
206
  </table>
@@ -237,13 +286,16 @@
237
 
238
  <script>
239
  const LABEL = { NORMAL: 'Bình thường', AGGRESSIVE: 'Lái xe hung hăng', DROWSY: 'Dấu hiệu buồn ngủ' };
240
- const COLOR = { NORMAL: '#22c55e', AGGRESSIVE: '#ef4444', DROWSY: '#eab308', INVALID: '#475569' };
 
 
241
  const $ = id => document.getElementById(id);
242
- let files = { acc: null, gps: null, folder: '' };
243
- let R = null; // kết quả phân tích
244
- let selected = null; // {t_start, t_end, eventIndex}
 
245
 
246
- // ---------------- tiện ích hiển thị ----------------
247
  function clock(sec) {
248
  sec = Math.max(0, Math.round(sec));
249
  const h = Math.floor(sec / 3600), m = Math.floor(sec % 3600 / 60), s = sec % 60;
@@ -257,30 +309,63 @@ function duration(sec) {
257
  if (m) return s ? `${m} phút ${s} giây` : `${m} phút`;
258
  return `${s} giây`;
259
  }
260
- const rel = t => t - R.trip.start; // thời điểm tính từ đầu chuyến
 
 
 
 
261
 
262
- // ---------------- trạng thái server ----------------
263
  fetch('api/status').then(r => r.json()).then(s => {
 
264
  $('statusDot').className = 'dot ' + (s.ready ? 'ok' : 'bad');
265
  $('statusText').textContent = s.ready ? 'Hệ thống sẵn sàng' : 'Chưa có model AI';
 
 
266
  if (!s.ready) showError('Hệ thống chưa có model AI nên chưa phân tích được. Chi tiết: ' + s.message);
 
 
 
 
 
 
 
267
  }).catch(() => { $('statusText').textContent = 'Không kết nối được máy chủ'; $('statusDot').className = 'dot bad'; });
268
 
269
  // ---------------- chọn file ----------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  function setFiles() {
271
- $('accState').textContent = '• Dữ liệu cảm biến chuyển động: ' + (files.acc ? files.acc.name : 'chưa có');
272
- $('accState').className = files.acc ? 'ok' : 'miss';
273
- $('gpsState').textContent = '• Dữ liệu GPS (không bắt buộc): ' + (files.gps ? files.gps.name : 'chưa có');
274
- $('gpsState').className = files.gps ? 'ok' : 'miss';
275
- $('runBtn').disabled = !files.acc;
 
 
 
 
 
276
  }
277
  $('pickDir').addEventListener('change', e => {
278
  const list = [...e.target.files];
279
  const find = n => list.find(f => f.name.toUpperCase() === n);
280
  files.acc = find('RAW_ACCELEROMETERS.TXT') || null;
281
  files.gps = find('RAW_GPS.TXT') || null;
 
282
  files.folder = list.length ? (list[0].webkitRelativePath || '').split('/')[0] : '';
283
- // Dữ liệu UAH: tên thư mục chứa mã tài xế (D1..D6) -> điền sẵn nếu ô đang trống
284
  const m = files.folder.match(/-(D\d)-/);
285
  if (m && !$('driver').value) $('driver').value = m[1];
286
  if (!files.acc) showError('Không thấy file RAW_ACCELEROMETERS.txt trong thư mục đã chọn.'); else hideError();
@@ -288,66 +373,123 @@ $('pickDir').addEventListener('change', e => {
288
  });
289
  $('pickAcc').addEventListener('change', e => { files.acc = e.target.files[0] || null; files.folder = ''; hideError(); setFiles(); });
290
  $('pickGps').addEventListener('change', e => { files.gps = e.target.files[0] || null; setFiles(); });
 
291
 
292
- function showError(msg) { $('errBox').textContent = msg; $('errBox').hidden = false; }
293
- function hideError() { $('errBox').hidden = true; }
294
-
295
- // ---------------- gọi phân tích ----------------
296
- $('runBtn').addEventListener('click', async () => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
  const fd = new FormData();
298
  fd.append('acc_file', files.acc);
299
  if (files.gps) fd.append('gps_file', files.gps);
300
- $('runBtn').disabled = true; $('runBtn').textContent = 'Đang phân tích, vui lòng đợi…'; hideError();
301
- try {
302
- const res = await fetch('api/analyze', { method: 'POST', body: fd });
303
- const body = await res.json();
304
- if (!res.ok) throw new Error(body.detail || 'Có lỗi khi phân tích.');
305
- R = body; render();
306
- } catch (err) {
307
- showError(err.message);
308
- } finally {
309
- $('runBtn').disabled = !files.acc; $('runBtn').textContent = 'Phân tích chuyến đi';
310
- }
311
  });
 
 
312
 
313
- // ---------------- hiển thị kết quả ----------------
314
  function render() {
315
- const T = R.trip;
316
  $('tripPanel').hidden = false; $('resultPanel').hidden = false;
317
- $('tripName').textContent = files.folder ? files.folder : '';
318
- $('iDriver').textContent = $('driver').value.trim() || '—';
319
- $('iPlate').textContent = $('plate').value.trim() || '—';
320
  $('iDur').textContent = duration(T.duration);
321
  $('iDist').textContent = T.distance_km != null ? T.distance_km.toFixed(1) + ' km' : 'Cần file GPS';
322
  $('iSpeed').textContent = T.max_speed != null ? Math.round(T.max_speed) + ' km/h' : 'Cần file GPS';
323
- $('iCover').textContent = `${Math.round(T.analysed_seconds / T.duration * 100)}% chuyến`;
324
- // Với dữ liệu thử nghiệm UAH, tên thư mục cho biết kiểu lái thật -> hiện để người kiểm thử đối chiếu
325
- const ref = files.folder.match(/-(NORMAL|AGGRESSIVE|DROWSY)\d?-/);
326
- $('refLabel').hidden = !ref;
327
- if (ref) $('refLabel').textContent = `Dữ liệu thử nghiệm: chuyến này được ghi khi tài xế được yêu cầu lái "${LABEL[ref[1]]}". Dùng để đối chiếu với kết luận của AI.`;
328
-
329
- // Kết luận
330
- const abn = T.share.AGGRESSIVE + T.share.DROWSY;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331
  const v = abn < 0.15 ? ['Lái xe ổn định', COLOR.NORMAL] : abn < 0.4 ? ['Cần chú ý', COLOR.DROWSY] : ['Cần kiểm tra kỹ', COLOR.AGGRESSIVE];
332
  $('vBadge').textContent = v[0];
333
  $('vBadge').style.cssText = `color:${v[1]}; border:2px solid ${v[1]}; background:${v[1]}22`;
334
- const nA = R.events.filter(e => e.label === 'AGGRESSIVE').length, nD = R.events.filter(e => e.label === 'DROWSY').length;
335
  const parts = [];
336
  if (nA) parts.push(`<b>${nA}</b> đoạn lái hung hăng`);
337
  if (nD) parts.push(`<b>${nD}</b> đoạn có dấu hiệu buồn ngủ`);
338
  $('vText').innerHTML = (parts.length ? 'Phát hiện ' + parts.join(' và ') + '.' : 'Không phát hiện đoạn bất thường đáng kể.') +
339
- `<br>Cả chuyến giống nhất với kiểu lái: <b>${LABEL[T.trip_label]}</b>.`;
 
340
  $('bars').innerHTML = '';
341
  for (const c of ['NORMAL', 'AGGRESSIVE', 'DROWSY']) {
342
- const pct = (T.share[c] * 100).toFixed(1);
343
  $('bars').insertAdjacentHTML('beforeend', `<div class="bar-row"><div class="bar-label">
344
- <span style="color:${COLOR[c]}">${LABEL[c]} · ${duration(T.seconds[c])}</span><span>${pct}%</span></div>
345
  <div class="bar-bg"><div class="bar-fg" style="width:${pct}%; background:${COLOR[c]}"></div></div></div>`);
346
  }
347
-
348
  renderTimeline(); renderEvents(); renderSuggestions();
349
- if (R.events.length) select(R.events[0].t_start, R.events[0].t_end, 0);
350
- else { const w = R.windows.find(w => w.valid); select(w.t_start, w.t_end, null); }
351
  }
352
 
353
  function renderTimeline() {
@@ -356,11 +498,12 @@ function renderTimeline() {
356
  tl.innerHTML = '';
357
  for (const w of R.windows) {
358
  const d = document.createElement('div');
359
- d.className = 'seg';
360
  d.style.left = (rel(w.t_start) / D * 100) + '%';
361
  d.style.width = Math.max((w.t_end - w.t_start) / D * 100, 0.15) + '%';
362
- d.style.background = w.valid ? COLOR[w.label] : COLOR.INVALID;
363
- d.title = `${clock(rel(w.t_start))}: ` + (w.valid ? LABEL[w.label] : 'Thiếu dữ liệu (' + w.reason + ')');
 
364
  tl.appendChild(d);
365
  }
366
  const cur = document.createElement('div'); cur.className = 'cursor'; cur.id = 'cursor'; tl.appendChild(cur);
@@ -369,18 +512,18 @@ function renderTimeline() {
369
  const box = tl.getBoundingClientRect();
370
  const t = T.start + (e.clientX - box.left) / box.width * D;
371
  const w = R.windows.reduce((a, b) => Math.abs((b.t_start + b.t_end) / 2 - t) < Math.abs((a.t_start + a.t_end) / 2 - t) ? b : a);
372
- const ei = R.events.findIndex(ev => t >= ev.t_start && t <= ev.t_end);
373
- if (ei >= 0) select(R.events[ei].t_start, R.events[ei].t_end, ei); else select(w.t_start, w.t_end, null);
374
  };
375
  }
376
 
377
  function renderEvents() {
378
- const body = $('evBody'); body.innerHTML = '';
379
- $('evCount').textContent = R.events.length ? `${R.events.length} đoạn` : '';
380
- $('evEmpty').hidden = R.events.length > 0;
381
  $('evEmpty').textContent = 'Không có đoạn nào bất thường đáng kể.';
382
- $('evTable').hidden = R.events.length === 0;
383
- R.events.forEach((e, i) => {
384
  const tr = document.createElement('tr'); tr.id = 'ev' + i;
385
  tr.innerHTML = `<td style="font-weight:700; color:#38bdf8">${clock(rel(e.t_start))}</td>
386
  <td style="font-weight:700; color:${COLOR[e.label]}">${LABEL[e.label]}</td>
@@ -393,17 +536,19 @@ function renderEvents() {
393
  }
394
 
395
  function renderSuggestions() {
396
- const T = R.trip, ul = $('sugg'); ul.innerHTML = '';
397
  const add = (cls, html) => ul.insertAdjacentHTML('beforeend', `<li class="${cls}">${html}</li>`);
398
- const longest = lab => R.events.filter(e => e.label === lab).sort((a, b) => (b.t_end - b.t_start) - (a.t_end - a.t_start))[0];
399
- const evA = R.events.filter(e => e.label === 'AGGRESSIVE'), evD = R.events.filter(e => e.label === 'DROWSY');
400
- if (!R.events.length) add('green', 'Chuyến đi không có đoạn bất thường đáng kể. Không cần xử lý thêm.');
401
  if (evA.length) { const l = longest('AGGRESSIVE');
402
  add('red', `Xem lại <b>${evA.length}</b> đoạn lái hung hăng. Đoạn dài nhất lúc <b>${clock(rel(l.t_start))}</b>, kéo dài ${duration(l.t_end - l.t_start)}.`); }
403
  if (evD.length) { const l = longest('DROWSY');
404
  add('amber', `Xem lại <b>${evD.length}</b> đoạn có dấu hiệu buồn ngủ. Đoạn dài nhất lúc <b>${clock(rel(l.t_start))}</b>, kéo dài ${duration(l.t_end - l.t_start)}. Nếu đúng, nhắc tài xế nghỉ ngơi đủ trước ca lái.`); }
405
- if (T.share.AGGRESSIVE + T.share.DROWSY >= 0.4) add('red', 'Tỉ lệ thời gian lái bất thường cao. Nên trao đổi trực tiếp với tài xế về chuyến đi này.');
406
- const miss = 1 - T.analysed_seconds / T.duration;
 
 
407
  if (miss > 0.2) add('', `Khoảng ${Math.round(miss * 100)}% chuyến đi thiếu dữ liệu cảm biến nên chưa được phân tích. Kết quả có thể chưa đầy đủ.`);
408
  add('', 'Kết quả AI chỉ để tham khảo. Hãy xem lại từng đoạn trước khi đưa ra kết luận về tài xế.');
409
  }
@@ -411,17 +556,47 @@ function renderSuggestions() {
411
  // ---------------- chọn một đoạn ----------------
412
  function select(t0, t1, ei) {
413
  selected = { t0, t1, ei };
414
- const T = R.trip;
415
- const c = $('cursor');
416
  c.style.left = (rel(t0) / T.duration * 100) + '%';
417
  c.style.width = Math.max((t1 - t0) / T.duration * 100, 0.4) + '%';
418
  document.querySelectorAll('#evBody tr').forEach(tr => tr.classList.remove('sel'));
419
  document.querySelectorAll('#evBody .btn-sm').forEach(b => { b.classList.remove('on'); b.textContent = 'Xem'; });
420
- if (ei != null) { $('ev' + ei).classList.add('sel'); $('evb' + ei).classList.add('on'); $('evb' + ei).textContent = 'Đang xem'; }
421
  const label = `${clock(rel(t0))} – ${clock(rel(t1))}`;
422
  $('selTime').textContent = label; $('videoTime').textContent = 'Thời điểm: ' + label;
423
  $('tlInfo').textContent = 'Đang xem: ' + label;
424
- renderDetail(t0, t1);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425
  }
426
 
427
  // ---------------- biểu đồ SVG đơn giản ----------------
@@ -440,7 +615,7 @@ function chart(svg, { x0, x1, y0, y1, band, lines, yTicks, yFmt, dashed }) {
440
  if (dashed != null) el('line', { x1: L, x2: Rr, y1: Y(dashed), y2: Y(dashed), stroke: '#93c5fd', 'stroke-dasharray': '5,4' }, svg);
441
  for (const ln of lines) {
442
  if (!ln.pts.length) continue;
443
- el('path', { d: ln.pts.map((p, i) => (i ? 'L' : 'M') + X(p[0]).toFixed(1) + ',' + Y(p[1]).toFixed(1)).join(' '),
444
  fill: 'none', stroke: ln.color, 'stroke-width': 1.8 }, svg);
445
  }
446
  for (const f of [0, .5, 1]) {
@@ -455,9 +630,7 @@ function renderDetail(t0, t1) {
455
  $('detEmpty').hidden = true; $('detBox').hidden = false;
456
  const T = R.trip, S = R.series;
457
  const pad = Math.max(30, (t1 - t0) * 0.5);
458
- const x0 = Math.max(T.start, t0 - pad), x1 = Math.min(T.end, t1 + pad);
459
- const band = [t0, t1];
460
-
461
  if (S.speed) {
462
  const pts = slice(S.gps_t, S.speed, x0, x1);
463
  const top = niceMax(Math.max(10, ...pts.map(p => p[1])));
@@ -468,9 +641,11 @@ function renderDetail(t0, t1) {
468
  const mpts = slice(S.t, S.motion, x0, x1);
469
  const mtop = niceMax(Math.max(0.05, ...mpts.map(p => p[1])));
470
  chart($('chMotion'), { x0, x1, y0: 0, y1: mtop, band, lines: [{ pts: mpts, color: '#a78bfa' }], yTicks: [0, mtop / 2, mtop], yFmt: v => v.toFixed(2) + 'g' });
471
-
472
- const wins = R.windows.filter(w => w.valid && w.t_end >= x0 && w.t_start <= x1);
473
- const step = idx => { const pts = []; for (const w of wins) { pts.push([w.t_start, w.probs[idx]]); pts.push([w.t_end, w.probs[idx]]); } return pts; };
 
 
474
  chart($('chProb'), { x0, x1, y0: 0, y1: 1, band, dashed: 0.6, lines: [{ pts: step(1), color: COLOR.AGGRESSIVE }, { pts: step(2), color: COLOR.DROWSY }],
475
  yTicks: [0, 0.5, 1], yFmt: v => Math.round(v * 100) + '%' });
476
  }
 
7
  <style>
8
  :root {
9
  --bg: #0b1120; --panel: #111827; --line: #1f2937; --soft: #1e293b; --muted: #94a3b8; --text: #f1f5f9;
10
+ --normal: #22c55e; --aggr: #ef4444; --drowsy: #eab308; --invalid: #475569; --none: #2b3648; --accent: #2563eb;
11
  }
12
  * { box-sizing: border-box; margin: 0; padding: 0; }
13
  body { background: #020617; color: var(--text); font-family: 'Segoe UI', Roboto, Arial, sans-serif; font-size: 14px; padding: 12px; }
 
25
  .dot.ok { background: var(--normal); box-shadow: 0 0 8px var(--normal); }
26
  .dot.bad { background: var(--aggr); }
27
 
28
+ .grid { display: grid; grid-template-columns: 340px minmax(0, 1fr) 430px; gap: 12px; align-items: start; }
29
  @media (max-width: 1250px) { .grid { grid-template-columns: 1fr; } }
30
  .col { display: flex; flex-direction: column; gap: 12px; min-width: 0; }
31
  .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; }
 
34
  .ph small { text-transform: none; font-weight: 600; color: var(--muted); font-size: 12px; }
35
  .hint { font-size: 12.5px; color: var(--muted); line-height: 1.45; }
36
 
37
+ .demo { background: linear-gradient(135deg, rgba(37,99,235,.18), rgba(14,165,233,.08)); border: 1px solid #1d4ed8; }
38
+ .demo .name { font-weight: 700; font-size: 14.5px; margin-bottom: 2px; }
39
  label.f { display: block; font-size: 12.5px; color: var(--muted); margin: 8px 0 4px; }
40
  input[type=text] { width: 100%; background: var(--soft); border: 1px solid #334155; color: var(--text);
41
  border-radius: 6px; padding: 7px 9px; font-size: 14px; }
 
44
  text-align: center; cursor: pointer; font-size: 13.5px; font-weight: 600; color: #93c5fd; margin-top: 8px; }
45
  .pick input { display: none; }
46
  .files { font-size: 12.5px; margin-top: 6px; line-height: 1.6; }
47
+ .files .ok { color: #4ade80; } .files .miss { color: var(--muted); } .files .bad { color: #fca5a5; }
48
  details { margin-top: 8px; font-size: 12.5px; color: var(--muted); }
49
  details summary { cursor: pointer; color: #93c5fd; }
50
  .btn { display: block; width: 100%; border: 0; border-radius: 7px; padding: 10px; font-size: 14.5px; font-weight: 700;
 
55
  .btn-sm.on { background: var(--accent); border-color: #3b82f6; color: #fff; }
56
  .err { background: rgba(239,68,68,.12); border: 1px solid var(--aggr); color: #fca5a5; border-radius: 7px;
57
  padding: 8px 10px; font-size: 13px; margin-top: 10px; }
58
+ .warn { background: rgba(234,179,8,.10); border: 1px solid var(--drowsy); color: #fde68a; border-radius: 7px;
59
+ padding: 8px 10px; font-size: 12.5px; margin-top: 8px; line-height: 1.45; }
60
+ .prog { margin-top: 10px; font-size: 13px; color: #bfdbfe; }
61
+ .prog .bar { height: 6px; border-radius: 3px; background: var(--soft); overflow: hidden; margin-top: 6px; }
62
+ .prog .bar div { height: 100%; width: 30%; background: var(--accent); animation: slide 1.2s infinite ease-in-out; }
63
+ @keyframes slide { 0% { margin-left: -30%; } 100% { margin-left: 100%; } }
64
+
65
+ .seg { display: flex; gap: 6px; flex-wrap: wrap; }
66
+ .seg button { flex: 1; min-width: 110px; background: var(--soft); border: 1px solid #475569; color: #cbd5e1; border-radius: 6px;
67
+ padding: 7px 8px; font-size: 13px; font-weight: 600; cursor: pointer; }
68
+ .seg button.on { background: var(--accent); border-color: #3b82f6; color: #fff; }
69
+ .seg button:disabled { opacity: .4; cursor: not-allowed; }
70
 
71
  .info { display: grid; grid-template-columns: 1fr 1fr; gap: 10px 8px; }
72
  .info label { display: block; font-size: 12px; color: #64748b; }
 
80
  .bar-bg { height: 9px; background: var(--soft); border-radius: 5px; overflow: hidden; }
81
  .bar-fg { height: 100%; }
82
  .note { margin-top: 10px; font-size: 12px; color: var(--muted); border-top: 1px solid var(--line); padding-top: 8px; line-height: 1.45; }
83
+ table.cmp { width: 100%; border-collapse: collapse; font-size: 12.5px; margin-top: 8px; }
84
+ table.cmp td, table.cmp th { padding: 5px 4px; border-bottom: 1px solid var(--soft); text-align: left; }
85
+ table.cmp th { color: #64748b; font-size: 11.5px; text-transform: uppercase; }
86
+
87
+ .video-box { min-height: 200px; border-radius: 8px; border: 1px solid #334155; background: #020617; display: flex;
88
+ flex-direction: column; align-items: center; justify-content: center; gap: 6px; text-align: center; padding: 10px;
89
+ user-select: none; }
90
+ .video-box img { width: 100%; max-width: 576px; border-radius: 6px; pointer-events: none; }
91
+ .strip { display: flex; gap: 4px; margin-top: 8px; overflow-x: auto; }
92
+ .strip div { flex: 0 0 auto; cursor: pointer; border: 2px solid transparent; border-radius: 4px; text-align: center;
93
+ font-size: 10.5px; color: var(--muted); }
94
+ .strip div.on { border-color: #fff; }
95
+ .strip img { width: 96px; height: 54px; display: block; border-radius: 3px; pointer-events: none; }
96
 
97
  .timeline { position: relative; height: 26px; border-radius: 6px; overflow: hidden; background: var(--soft);
98
  border: 1px solid #334155; margin: 4px 0 6px; cursor: pointer; }
99
+ .timeline div.seg2 { position: absolute; top: 0; bottom: 0; }
100
  .timeline .cursor { position: absolute; top: -2px; bottom: -2px; border: 2px solid #fff; border-radius: 3px;
101
  box-shadow: 0 0 6px #fff; pointer-events: none; }
102
  .ticks { display: flex; justify-content: space-between; font-size: 12px; color: var(--muted); }
103
  .legend { display: flex; gap: 14px; flex-wrap: wrap; font-size: 12.5px; margin-top: 8px; }
104
  .legend i { display: inline-block; width: 11px; height: 11px; border-radius: 3px; margin-right: 5px; vertical-align: -1px; }
105
 
106
+ table.ev { width: 100%; border-collapse: collapse; font-size: 13.5px; }
107
+ table.ev th { text-align: left; color: #64748b; font-size: 12px; padding: 6px 6px; border-bottom: 1px solid var(--line); text-transform: uppercase; }
108
+ table.ev td { padding: 8px 6px; border-bottom: 1px solid var(--soft); vertical-align: middle; }
109
  tr.sel { background: rgba(37,99,235,.14); }
110
  .lvl { border-radius: 10px; padding: 2px 8px; font-size: 12px; font-weight: 700; white-space: nowrap; border: 1px solid; }
111
  .lvl.high { color: #f87171; border-color: var(--aggr); background: rgba(239,68,68,.15); }
 
139
  <div class="grid">
140
  <!-- ================= CỘT TRÁI ================= -->
141
  <div class="col">
142
+ <div class="panel demo" id="demoPanel" hidden>
143
+ <div class="ph"><span>Chuyến mẫu có sẵn</span><small>không cần tải file</small></div>
144
+ <div class="name" id="demoName"></div>
145
+ <div class="hint" id="demoHint"></div>
146
+ <button class="btn" id="demoBtn">▶ Phân tích chuyến mẫu</button>
147
+ </div>
148
+
149
  <div class="panel">
150
+ <div class="ph"><span>Hoặc tải chuyến đi của bạn</span></div>
151
  <div class="row2">
152
  <div><label class="f">Mã tài xế</label><input type="text" id="driver" placeholder="VD: TX-0123"></div>
153
  <div><label class="f">Biển số xe</label><input type="text" id="plate" placeholder="VD: 30A-123.45"></div>
 
155
  <label class="pick">📁 Chọn thư mục chuyến đi
156
  <input type="file" id="pickDir" webkitdirectory multiple>
157
  </label>
158
+ <div class="files">
159
+ <div class="miss" id="accState">• Cảm biến chuyển động (bắt buộc): chưa có</div>
160
+ <div class="miss" id="gpsState">• GPS (không bắt buộc): chưa có</div>
161
+ <div class="miss" id="vidState">• Video hành trình (không bắt buộc): chưa có</div>
162
  </div>
163
  <details>
164
  <summary>Hoặc chọn từng file</summary>
165
+ <label class="f">Cảm biến chuyển động (RAW_ACCELEROMETERS.txt)</label>
166
+ <input type="file" id="pickAcc" accept=".txt,.csv">
167
+ <label class="f">GPS (RAW_GPS.txt)</label>
168
+ <input type="file" id="pickGps" accept=".txt,.csv">
169
+ <label class="f">Video hành trình (.mp4)</label>
170
+ <input type="file" id="pickVid" accept=".mp4,.mov,.avi,.mkv,.m4v">
171
  </details>
172
+ <div class="hint" id="limitHint" style="margin-top:8px"></div>
173
  <button class="btn" id="runBtn" disabled>Phân tích chuyến đi</button>
174
+ <div class="prog" id="progBox" hidden><span id="progText"></span><div class="bar"><div></div></div></div>
175
  <div class="err" id="errBox" hidden></div>
176
  </div>
177
 
 
190
  </div>
191
 
192
  <div class="panel" id="resultPanel" hidden>
193
+ <div class="ph"><span>Kết luận</span><small id="modelName"></small></div>
194
  <div class="verdict">
195
  <div class="vbadge" id="vBadge"></div>
196
  <div class="vtext" id="vText"></div>
197
  </div>
198
  <div id="bars"></div>
199
+ <div class="chart-title" style="margin-top:10px">So sánh 3 cách phân tích</div>
200
+ <table class="cmp"><thead><tr><th>Cách</th><th>Cả chuyến giống</th><th>Bất thường</th></tr></thead><tbody id="cmpBody"></tbody></table>
201
  <details>
202
  <summary>Kết luận được tính thế nào?</summary>
203
+ <p style="margin-top:6px; line-height:1.5">Chuyến đi được chia thành các đoạn 5 giây. Với mỗi đoạn, AI cho biết đoạn đó giống
204
+ kiểu lái nào nhất. Có 3 cách: chỉ dùng <b>cảm biến chuyển động</b>, chỉ dùng <b>video</b>, hoặc <b>kết hợp</b> cả hai.
205
+ Nếu tổng thời gian lái hung hăng và buồn ngủ dưới 15% thì <b>Lái xe ổn định</b>, từ 15% đến dưới 40% thì
206
+ <b>Cần chú ý</b>, từ 40% trở lên thì <b>Cần kiểm tra kỹ</b>.</p>
207
  </details>
208
  <div class="note">Kết quả do AI tạo ra, chỉ để tham khảo. Nhân viên cần xem lại các đoạn được đánh dấu trước khi kết luận về tài xế.</div>
209
  </div>
 
211
 
212
  <!-- ================= CỘT GIỮA ================= -->
213
  <div class="col">
214
+ <div class="panel">
215
+ <div class="ph"><span>Xem kết quả theo</span></div>
216
+ <div class="seg" id="modelSeg">
217
+ <button data-m="fusion" disabled>Kết hợp video + cảm biến</button>
218
+ <button data-m="video" disabled>Chỉ video</button>
219
+ <button data-m="sensor" disabled>Chỉ cảm biến</button>
220
+ </div>
221
+ </div>
222
+
223
  <div class="panel">
224
  <div class="ph"><span>Video hành trình</span><small id="videoTime"></small></div>
225
+ <div class="video-box" id="videoBox" oncontextmenu="return false">
226
+ <div style="font-size:30px">🎥</div>
227
+ <div class="hint">Chọn chuyến mẫu hoặc tải chuyến đi kèm video để xem khung hình tại thời điểm bạn chọn.</div>
 
228
  </div>
229
+ <div class="strip" id="strip" oncontextmenu="return false"></div>
230
+ <div class="warn" id="videoWarn" hidden></div>
231
  </div>
232
 
233
  <div class="panel">
 
241
  <span><i style="background:var(--aggr)"></i>Lái xe hung hăng</span>
242
  <span><i style="background:var(--drowsy)"></i>Dấu hiệu buồn ngủ</span>
243
  <span><i style="background:var(--invalid)"></i>Thiếu dữ liệu</span>
244
+ <span><i style="background:var(--none)"></i>Không có kết quả cho cách này</span>
245
  </div>
246
  </div>
247
  </div>
 
249
  <div class="panel">
250
  <div class="ph"><span>Các đoạn cần xem lại</span><small id="evCount"></small></div>
251
  <div id="evEmpty" class="empty">Chưa có kết quả.</div>
252
+ <table class="ev" id="evTable" hidden>
253
  <thead><tr><th>Thời điểm</th><th>Hành vi</th><th>Kéo dài</th><th>AI chắc chắn</th><th></th></tr></thead>
254
  <tbody id="evBody"></tbody>
255
  </table>
 
286
 
287
  <script>
288
  const LABEL = { NORMAL: 'Bình thường', AGGRESSIVE: 'Lái xe hung hăng', DROWSY: 'Dấu hiệu buồn ngủ' };
289
+ const COLOR = { NORMAL: '#22c55e', AGGRESSIVE: '#ef4444', DROWSY: '#eab308', INVALID: '#475569', NONE: '#2b3648' };
290
+ const MODEL_NAME = { fusion: 'Kết hợp video + cảm biến', video: 'Chỉ video', sensor: 'Chỉ cảm biến' };
291
+ const TEXT_EXT = ['.txt', '.csv'], VIDEO_EXT = ['.mp4', '.mov', '.avi', '.mkv', '.m4v'];
292
  const $ = id => document.getElementById(id);
293
+ let LIMITS = { text_mb: 20, video_mb: 300 };
294
+ let STATUS = null;
295
+ let files = { acc: null, gps: null, vid: null, folder: '' };
296
+ let R = null, M = 'sensor', selected = null, busy = false, sourceLabel = '';
297
 
298
+ // ---------------- tiện ích ----------------
299
  function clock(sec) {
300
  sec = Math.max(0, Math.round(sec));
301
  const h = Math.floor(sec / 3600), m = Math.floor(sec % 3600 / 60), s = sec % 60;
 
309
  if (m) return s ? `${m} phút ${s} giây` : `${m} phút`;
310
  return `${s} giây`;
311
  }
312
+ const mb = b => (b / 1048576).toFixed(b < 10485760 ? 1 : 0) + ' MB';
313
+ const ext = n => (n.match(/\.[^.]+$/) || [''])[0].toLowerCase();
314
+ const rel = t => t - R.trip.start;
315
+ function showError(msg) { $('errBox').textContent = msg; $('errBox').hidden = false; }
316
+ function hideError() { $('errBox').hidden = true; }
317
 
318
+ // ---------------- trạng thái máy chủ ----------------
319
  fetch('api/status').then(r => r.json()).then(s => {
320
+ STATUS = s; LIMITS = s.limits || LIMITS;
321
  $('statusDot').className = 'dot ' + (s.ready ? 'ok' : 'bad');
322
  $('statusText').textContent = s.ready ? 'Hệ thống sẵn sàng' : 'Chưa có model AI';
323
+ $('limitHint').textContent = `Giới hạn: file cảm biến/GPS tối đa ${LIMITS.text_mb} MB, video tối đa ${LIMITS.video_mb} MB.` +
324
+ (s.video ? '' : ' Máy chủ chưa có model video nên chỉ phân tích dữ liệu cảm biến.');
325
  if (!s.ready) showError('Hệ thống chưa có model AI nên chưa phân tích được. Chi tiết: ' + s.message);
326
+ if (s.demo) {
327
+ $('demoPanel').hidden = false;
328
+ $('demoName').textContent = s.demo.title || s.demo.trip_name;
329
+ $('demoHint').textContent = `Dữ liệu cảm biến + video, ${duration(s.demo.duration || 0)}. ` +
330
+ (s.demo.reference ? `Chuyến này được ghi khi tài xế được yêu cầu lái "${s.demo.reference}". ` : '') +
331
+ 'Tài xế này không có trong dữ liệu dùng để huấn luyện AI.';
332
+ }
333
  }).catch(() => { $('statusText').textContent = 'Không kết nối được máy chủ'; $('statusDot').className = 'dot bad'; });
334
 
335
  // ---------------- chọn file ----------------
336
+ function checkFile(f, kind) {
337
+ if (!f) return null;
338
+ const e = ext(f.name);
339
+ if (kind === 'vid') {
340
+ if (!VIDEO_EXT.includes(e)) return 'không phải file video được hỗ trợ (.mp4)';
341
+ if (f.size > LIMITS.video_mb * 1048576) return `quá lớn (${mb(f.size)}, tối đa ${LIMITS.video_mb} MB)`;
342
+ } else {
343
+ if (VIDEO_EXT.includes(e)) return 'đây là file video, hãy chọn ở ô video';
344
+ if (!TEXT_EXT.includes(e)) return 'chỉ nhận file .txt';
345
+ if (f.size > LIMITS.text_mb * 1048576) return `quá lớn (${mb(f.size)}, tối đa ${LIMITS.text_mb} MB)`;
346
+ }
347
+ if (f.size === 0) return 'file trống';
348
+ return null;
349
+ }
350
  function setFiles() {
351
+ const rows = [['acc', 'accState', 'Cảm biến chuyển động (bắt buộc)'], ['gps', 'gpsState', 'GPS (không bắt buộc)'],
352
+ ['vid', 'vidState', 'Video hành trình (không bắt buộc)']];
353
+ let ok = true;
354
+ for (const [k, id, label] of rows) {
355
+ const f = files[k], err = checkFile(f, k);
356
+ $(id).textContent = `• ${label}: ` + (f ? `${f.name} (${mb(f.size)})` + (err ? ` — ${err}` : '') : 'chưa có');
357
+ $(id).className = !f ? 'miss' : err ? 'bad' : 'ok';
358
+ if (err) ok = false;
359
+ }
360
+ $('runBtn').disabled = busy || !files.acc || !ok;
361
  }
362
  $('pickDir').addEventListener('change', e => {
363
  const list = [...e.target.files];
364
  const find = n => list.find(f => f.name.toUpperCase() === n);
365
  files.acc = find('RAW_ACCELEROMETERS.TXT') || null;
366
  files.gps = find('RAW_GPS.TXT') || null;
367
+ files.vid = list.find(f => VIDEO_EXT.includes(ext(f.name))) || null;
368
  files.folder = list.length ? (list[0].webkitRelativePath || '').split('/')[0] : '';
 
369
  const m = files.folder.match(/-(D\d)-/);
370
  if (m && !$('driver').value) $('driver').value = m[1];
371
  if (!files.acc) showError('Không thấy file RAW_ACCELEROMETERS.txt trong thư mục đã chọn.'); else hideError();
 
373
  });
374
  $('pickAcc').addEventListener('change', e => { files.acc = e.target.files[0] || null; files.folder = ''; hideError(); setFiles(); });
375
  $('pickGps').addEventListener('change', e => { files.gps = e.target.files[0] || null; setFiles(); });
376
+ $('pickVid').addEventListener('change', e => { files.vid = e.target.files[0] || null; setFiles(); });
377
 
378
+ // ---------------- gửi phân tích + theo dõi tiến độ ----------------
379
+ function setBusy(b, text) {
380
+ busy = b;
381
+ $('progBox').hidden = !b; $('progText').textContent = text || '';
382
+ $('demoBtn').disabled = b;
383
+ setFiles();
384
+ }
385
+ async function postJob(url, body) {
386
+ let res;
387
+ try { res = await fetch(url, { method: 'POST', body }); }
388
+ catch (e) { throw new Error('Không gửi được dữ liệu lên máy chủ. Kiểm tra kết nối mạng rồi thử lại.'); }
389
+ let data = {};
390
+ try { data = await res.json(); } catch (e) { /* phản hồi không phải JSON */ }
391
+ if (!res.ok) {
392
+ if (res.status === 413 && !data.detail) throw new Error('Dữ liệu tải lên quá lớn.');
393
+ throw new Error(data.detail || `Máy chủ báo lỗi (${res.status}).`);
394
+ }
395
+ return data.job_id;
396
+ }
397
+ async function waitJob(jid) {
398
+ const t0 = Date.now();
399
+ let netFail = 0;
400
+ while (Date.now() - t0 < 20 * 60 * 1000) {
401
+ await new Promise(r => setTimeout(r, 1500));
402
+ let res, data;
403
+ try { res = await fetch('api/job/' + jid); data = await res.json(); netFail = 0; }
404
+ catch (e) { if (++netFail >= 5) throw new Error('Mất kết nối tới máy chủ khi đang phân tích.'); continue; }
405
+ if (!res.ok) throw new Error(data.detail || 'Không lấy được kết quả.');
406
+ if (data.status === 'done') return data.result;
407
+ if (data.status === 'error') throw new Error(data.error);
408
+ $('progText').textContent = data.status === 'queued'
409
+ ? `Đang chờ đến lượt (còn ${data.queue_position || 0} chuyến phía trước)…` : data.progress;
410
+ }
411
+ throw new Error('Phân tích quá lâu (hơn 20 phút). Hãy thử lại sau.');
412
+ }
413
+ async function runJob(url, body, label) {
414
+ hideError(); setBusy(true, 'Đang gửi dữ liệu…');
415
+ try {
416
+ const jid = await postJob(url, body);
417
+ const result = await waitJob(jid);
418
+ sourceLabel = label; R = result; render();
419
+ } catch (err) { showError(err.message); }
420
+ finally { setBusy(false); }
421
+ }
422
+ $('runBtn').addEventListener('click', () => {
423
  const fd = new FormData();
424
  fd.append('acc_file', files.acc);
425
  if (files.gps) fd.append('gps_file', files.gps);
426
+ if (files.vid) fd.append('video_file', files.vid);
427
+ fd.append('trip_name', files.folder || '');
428
+ runJob('api/analyze', fd, files.folder || files.acc.name);
 
 
 
 
 
 
 
 
429
  });
430
+ $('demoBtn').addEventListener('click', () => runJob('api/demo', null, 'demo'));
431
+ document.querySelectorAll('#modelSeg button').forEach(b => b.addEventListener('click', () => { M = b.dataset.m; renderModel(); }));
432
 
433
+ // ---------------- hiển thị ----------------
434
  function render() {
435
+ const T = R.trip, demo = R.demo && STATUS && STATUS.demo;
436
  $('tripPanel').hidden = false; $('resultPanel').hidden = false;
437
+ $('tripName').textContent = demo ? `Chuyến mẫu: ${STATUS.demo.trip_name}` : sourceLabel;
438
+ $('iDriver').textContent = demo ? (STATUS.demo.driver || '—') : ($('driver').value.trim() || '—');
439
+ $('iPlate').textContent = demo ? '—' : ($('plate').value.trim() || '—');
440
  $('iDur').textContent = duration(T.duration);
441
  $('iDist').textContent = T.distance_km != null ? T.distance_km.toFixed(1) + ' km' : 'Cần file GPS';
442
  $('iSpeed').textContent = T.max_speed != null ? Math.round(T.max_speed) + ' km/h' : 'Cần file GPS';
443
+ const sens = R.models.sensor;
444
+ $('iCover').textContent = `${Math.round(sens.analysed_seconds / T.duration * 100)}% chuyến`;
445
+ const refBeh = demo ? STATUS.demo.behavior : ((sourceLabel || '').match(/-(NORMAL|AGGRESSIVE|DROWSY)\d?-/) || [])[1];
446
+ $('refLabel').hidden = !refBeh;
447
+ if (refBeh) $('refLabel').textContent = `Dữ liệu thử nghiệm: chuyến này được ghi khi tài xế được yêu cầu lái "${LABEL[refBeh]}". Dùng để đối chiếu với kết luận của AI.`;
448
+
449
+ // so sánh 3 cách
450
+ $('cmpBody').innerHTML = '';
451
+ for (const m of ['fusion', 'video', 'sensor']) {
452
+ const s = R.models[m];
453
+ const tr = document.createElement('tr');
454
+ tr.innerHTML = s ? `<td>${MODEL_NAME[m]}</td><td style="color:${COLOR[s.trip_label]};font-weight:700">${LABEL[s.trip_label]}</td>
455
+ <td>${Math.round((s.share.AGGRESSIVE + s.share.DROWSY) * 100)}%</td>` : `<td>${MODEL_NAME[m]}</td><td colspan="2" style="color:var(--muted)">Không có</td>`;
456
+ $('cmpBody').appendChild(tr);
457
+ }
458
+ document.querySelectorAll('#modelSeg button').forEach(b => { b.disabled = !R.models[b.dataset.m]; });
459
+ M = ['fusion', 'video', 'sensor'].find(m => R.models[m]);
460
+
461
+ // video
462
+ const V = R.video || {};
463
+ $('videoWarn').hidden = !V.message || V.status === 'ok' && !R.demo;
464
+ $('videoWarn').textContent = V.message || '';
465
+ renderModel();
466
+ }
467
+
468
+ function renderModel() {
469
+ const S = R.models[M], T = R.trip;
470
+ document.querySelectorAll('#modelSeg button').forEach(b => b.classList.toggle('on', b.dataset.m === M));
471
+ $('modelName').textContent = MODEL_NAME[M];
472
+ const abn = S.share.AGGRESSIVE + S.share.DROWSY;
473
  const v = abn < 0.15 ? ['Lái xe ổn định', COLOR.NORMAL] : abn < 0.4 ? ['Cần chú ý', COLOR.DROWSY] : ['Cần kiểm tra kỹ', COLOR.AGGRESSIVE];
474
  $('vBadge').textContent = v[0];
475
  $('vBadge').style.cssText = `color:${v[1]}; border:2px solid ${v[1]}; background:${v[1]}22`;
476
+ const nA = S.events.filter(e => e.label === 'AGGRESSIVE').length, nD = S.events.filter(e => e.label === 'DROWSY').length;
477
  const parts = [];
478
  if (nA) parts.push(`<b>${nA}</b> đoạn lái hung hăng`);
479
  if (nD) parts.push(`<b>${nD}</b> đoạn có dấu hiệu buồn ngủ`);
480
  $('vText').innerHTML = (parts.length ? 'Phát hiện ' + parts.join(' và ') + '.' : 'Không phát hiện đoạn bất thường đáng kể.') +
481
+ `<br>Cả chuyến giống nhất với kiểu lái: <b>${LABEL[S.trip_label]}</b>.` +
482
+ (S.analysed_seconds < R.models.sensor.analysed_seconds * 0.95 ? `<br><span style="color:var(--muted)">Cách này phân tích được ${duration(S.analysed_seconds)} của chuyến.</span>` : '');
483
  $('bars').innerHTML = '';
484
  for (const c of ['NORMAL', 'AGGRESSIVE', 'DROWSY']) {
485
+ const pct = (S.share[c] * 100).toFixed(1);
486
  $('bars').insertAdjacentHTML('beforeend', `<div class="bar-row"><div class="bar-label">
487
+ <span style="color:${COLOR[c]}">${LABEL[c]} · ${duration(S.seconds[c])}</span><span>${pct}%</span></div>
488
  <div class="bar-bg"><div class="bar-fg" style="width:${pct}%; background:${COLOR[c]}"></div></div></div>`);
489
  }
 
490
  renderTimeline(); renderEvents(); renderSuggestions();
491
+ if (S.events.length) select(S.events[0].t_start, S.events[0].t_end, 0);
492
+ else { const w = R.windows.find(w => w[M]); select(w.t_start, w.t_end, null); }
493
  }
494
 
495
  function renderTimeline() {
 
498
  tl.innerHTML = '';
499
  for (const w of R.windows) {
500
  const d = document.createElement('div');
501
+ d.className = 'seg2';
502
  d.style.left = (rel(w.t_start) / D * 100) + '%';
503
  d.style.width = Math.max((w.t_end - w.t_start) / D * 100, 0.15) + '%';
504
+ const r = w[M];
505
+ d.style.background = !w.valid ? COLOR.INVALID : r ? COLOR[r.label] : COLOR.NONE;
506
+ d.title = `${clock(rel(w.t_start))}: ` + (!w.valid ? 'Thiếu dữ liệu (' + w.reason + ')' : r ? LABEL[r.label] : 'Không có kết quả cho cách này');
507
  tl.appendChild(d);
508
  }
509
  const cur = document.createElement('div'); cur.className = 'cursor'; cur.id = 'cursor'; tl.appendChild(cur);
 
512
  const box = tl.getBoundingClientRect();
513
  const t = T.start + (e.clientX - box.left) / box.width * D;
514
  const w = R.windows.reduce((a, b) => Math.abs((b.t_start + b.t_end) / 2 - t) < Math.abs((a.t_start + a.t_end) / 2 - t) ? b : a);
515
+ const evs = R.models[M].events, ei = evs.findIndex(ev => t >= ev.t_start && t <= ev.t_end);
516
+ if (ei >= 0) select(evs[ei].t_start, evs[ei].t_end, ei); else select(w.t_start, w.t_end, null);
517
  };
518
  }
519
 
520
  function renderEvents() {
521
+ const evs = R.models[M].events, body = $('evBody'); body.innerHTML = '';
522
+ $('evCount').textContent = evs.length ? `${evs.length} đoạn` : '';
523
+ $('evEmpty').hidden = evs.length > 0;
524
  $('evEmpty').textContent = 'Không có đoạn nào bất thường đáng kể.';
525
+ $('evTable').hidden = evs.length === 0;
526
+ evs.forEach((e, i) => {
527
  const tr = document.createElement('tr'); tr.id = 'ev' + i;
528
  tr.innerHTML = `<td style="font-weight:700; color:#38bdf8">${clock(rel(e.t_start))}</td>
529
  <td style="font-weight:700; color:${COLOR[e.label]}">${LABEL[e.label]}</td>
 
536
  }
537
 
538
  function renderSuggestions() {
539
+ const S = R.models[M], T = R.trip, ul = $('sugg'); ul.innerHTML = '';
540
  const add = (cls, html) => ul.insertAdjacentHTML('beforeend', `<li class="${cls}">${html}</li>`);
541
+ const longest = lab => S.events.filter(e => e.label === lab).sort((a, b) => (b.t_end - b.t_start) - (a.t_end - a.t_start))[0];
542
+ const evA = S.events.filter(e => e.label === 'AGGRESSIVE'), evD = S.events.filter(e => e.label === 'DROWSY');
543
+ if (!S.events.length) add('green', 'Chuyến đi không có đoạn bất thường đáng kể. Không cần xử lý thêm.');
544
  if (evA.length) { const l = longest('AGGRESSIVE');
545
  add('red', `Xem lại <b>${evA.length}</b> đoạn lái hung hăng. Đoạn dài nhất lúc <b>${clock(rel(l.t_start))}</b>, kéo dài ${duration(l.t_end - l.t_start)}.`); }
546
  if (evD.length) { const l = longest('DROWSY');
547
  add('amber', `Xem lại <b>${evD.length}</b> đoạn có dấu hiệu buồn ngủ. Đoạn dài nhất lúc <b>${clock(rel(l.t_start))}</b>, kéo dài ${duration(l.t_end - l.t_start)}. Nếu đúng, nhắc tài xế nghỉ ngơi đủ trước ca lái.`); }
548
+ if (S.share.AGGRESSIVE + S.share.DROWSY >= 0.4) add('red', 'Tỉ lệ thời gian lái bất thường cao. Nên trao đổi trực tiếp với tài xế về chuyến đi này.');
549
+ const labels = ['fusion', 'video', 'sensor'].filter(m => R.models[m]).map(m => R.models[m].trip_label);
550
+ if (new Set(labels).size > 1) add('', 'Các cách phân tích cho kết luận khác nhau. Nên xem trực tiếp khung hình video ở các đoạn được đánh dấu.');
551
+ const miss = 1 - R.models.sensor.analysed_seconds / T.duration;
552
  if (miss > 0.2) add('', `Khoảng ${Math.round(miss * 100)}% chuyến đi thiếu dữ liệu cảm biến nên chưa được phân tích. Kết quả có thể chưa đầy đủ.`);
553
  add('', 'Kết quả AI chỉ để tham khảo. Hãy xem lại từng đoạn trước khi đưa ra kết luận về tài xế.');
554
  }
 
556
  // ---------------- chọn một đoạn ----------------
557
  function select(t0, t1, ei) {
558
  selected = { t0, t1, ei };
559
+ const T = R.trip, c = $('cursor');
 
560
  c.style.left = (rel(t0) / T.duration * 100) + '%';
561
  c.style.width = Math.max((t1 - t0) / T.duration * 100, 0.4) + '%';
562
  document.querySelectorAll('#evBody tr').forEach(tr => tr.classList.remove('sel'));
563
  document.querySelectorAll('#evBody .btn-sm').forEach(b => { b.classList.remove('on'); b.textContent = 'Xem'; });
564
+ if (ei != null && $('ev' + ei)) { $('ev' + ei).classList.add('sel'); $('evb' + ei).classList.add('on'); $('evb' + ei).textContent = 'Đang xem'; }
565
  const label = `${clock(rel(t0))} – ${clock(rel(t1))}`;
566
  $('selTime').textContent = label; $('videoTime').textContent = 'Thời điểm: ' + label;
567
  $('tlInfo').textContent = 'Đang xem: ' + label;
568
+ renderVideo(t0, t1); renderDetail(t0, t1);
569
+ }
570
+
571
+ function renderVideo(t0, t1) {
572
+ const box = $('videoBox'), strip = $('strip');
573
+ strip.innerHTML = '';
574
+ const withThumb = R.windows.filter(w => w.thumb != null);
575
+ if (!withThumb.length) {
576
+ box.innerHTML = `<div style="font-size:30px">🎥</div><div class="hint">${R.video && R.video.status !== 'none'
577
+ ? 'Không có khung hình video cho chuyến này.' : 'Chuyến này không có video. Tải kèm file video để xem khung hình.'}</div>`;
578
+ return;
579
+ }
580
+ const mid = (t0 + t1) / 2;
581
+ let k = 0;
582
+ withThumb.forEach((w, i) => { if (Math.abs((w.t_start + w.t_end) / 2 - mid) < Math.abs((withThumb[k].t_start + withThumb[k].t_end) / 2 - mid)) k = i; });
583
+ const w = withThumb[k], far = Math.abs((w.t_start + w.t_end) / 2 - mid) > 10;
584
+ box.innerHTML = '';
585
+ const img = document.createElement('img');
586
+ img.src = 'data:image/jpeg;base64,' + R.thumbs[w.thumb]; img.draggable = false; img.alt = 'Khung hình video';
587
+ box.appendChild(img);
588
+ const cap = document.createElement('div'); cap.className = 'hint';
589
+ cap.textContent = `Khung hình giữa đoạn ${clock(rel(w.t_start))} – ${clock(rel(w.t_end))}` +
590
+ (far ? ' (đoạn gần nhất có video)' : '');
591
+ box.appendChild(cap);
592
+ for (let i = Math.max(0, k - 3); i <= Math.min(withThumb.length - 1, k + 3); i++) {
593
+ const ww = withThumb[i], d = document.createElement('div');
594
+ if (i === k) d.className = 'on';
595
+ const im = document.createElement('img'); im.src = 'data:image/jpeg;base64,' + R.thumbs[ww.thumb]; im.draggable = false;
596
+ d.appendChild(im); d.appendChild(document.createTextNode(clock(rel(ww.t_start))));
597
+ d.onclick = () => select(ww.t_start, ww.t_end, null);
598
+ strip.appendChild(d);
599
+ }
600
  }
601
 
602
  // ---------------- biểu đồ SVG đơn giản ----------------
 
615
  if (dashed != null) el('line', { x1: L, x2: Rr, y1: Y(dashed), y2: Y(dashed), stroke: '#93c5fd', 'stroke-dasharray': '5,4' }, svg);
616
  for (const ln of lines) {
617
  if (!ln.pts.length) continue;
618
+ el('path', { d: ln.pts.map((p, i) => (p[2] ? 'M' : (i ? 'L' : 'M')) + X(p[0]).toFixed(1) + ',' + Y(p[1]).toFixed(1)).join(' '),
619
  fill: 'none', stroke: ln.color, 'stroke-width': 1.8 }, svg);
620
  }
621
  for (const f of [0, .5, 1]) {
 
630
  $('detEmpty').hidden = true; $('detBox').hidden = false;
631
  const T = R.trip, S = R.series;
632
  const pad = Math.max(30, (t1 - t0) * 0.5);
633
+ const x0 = Math.max(T.start, t0 - pad), x1 = Math.min(T.end, t1 + pad), band = [t0, t1];
 
 
634
  if (S.speed) {
635
  const pts = slice(S.gps_t, S.speed, x0, x1);
636
  const top = niceMax(Math.max(10, ...pts.map(p => p[1])));
 
641
  const mpts = slice(S.t, S.motion, x0, x1);
642
  const mtop = niceMax(Math.max(0.05, ...mpts.map(p => p[1])));
643
  chart($('chMotion'), { x0, x1, y0: 0, y1: mtop, band, lines: [{ pts: mpts, color: '#a78bfa' }], yTicks: [0, mtop / 2, mtop], yFmt: v => v.toFixed(2) + 'g' });
644
+ // đường bậc thang theo từng đoạn; ngắt nét ở đoạn không có kết quả
645
+ const wins = R.windows.filter(w => w.t_end >= x0 && w.t_start <= x1);
646
+ const step = idx => { const pts = []; let gap = true;
647
+ for (const w of wins) { const r = w[M]; if (!r) { gap = true; continue; }
648
+ pts.push([w.t_start, r.probs[idx], gap]); pts.push([w.t_end, r.probs[idx], false]); gap = false; } return pts; };
649
  chart($('chProb'), { x0, x1, y0: 0, y1: 1, band, dashed: 0.6, lines: [{ pts: step(1), color: COLOR.AGGRESSIVE }, { pts: step(2), color: COLOR.DROWSY }],
650
  yTicks: [0, 0.5, 1], yFmt: v => Math.round(v * 100) + '%' });
651
  }
swin_fusion.py ADDED
@@ -0,0 +1,720 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Bản sao NGUYÊN VẸN của ../models/SwinTransformer_fusion.py (model fusion, Stage 4).
2
+ # Chép vào đây để thư mục web/ tự chạy được khi deploy. Không sửa file này.
3
+
4
+ # -*- coding: utf-8 -*-
5
+ """
6
+ @File : SWT_V2_1D.py
7
+ @Time : 2022/8/14 16:15
8
+ @Author : HUANG Dong
9
+ @Version : 0.0.1
10
+ @Contact : huang_dong@tju.edu.cn
11
+ @Desc : None
12
+ """
13
+ import math
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ import torch.utils.checkpoint as checkpoint
19
+ from torch.nn.init import trunc_normal_
20
+ import numpy as np
21
+
22
+
23
+ def drop_path(x, drop_prob: float = 0., training: bool = False, scale_by_keep: bool = True):
24
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
25
+
26
+ This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
27
+ the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
28
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
29
+ changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
30
+ 'survival rate' as the argument.
31
+
32
+ """
33
+ if drop_prob == 0. or not training:
34
+ return x
35
+ keep_prob = 1 - drop_prob
36
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
37
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
38
+ if keep_prob > 0.0 and scale_by_keep:
39
+ random_tensor.div_(keep_prob)
40
+ return x * random_tensor
41
+
42
+
43
+ class DropPath(nn.Module):
44
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
45
+ """
46
+ def __init__(self, drop_prob: float = 0., scale_by_keep: bool = True):
47
+ super(DropPath, self).__init__()
48
+ self.drop_prob = drop_prob
49
+ self.scale_by_keep = scale_by_keep
50
+
51
+ def forward(self, x):
52
+ return drop_path(x, self.drop_prob, self.training, self.scale_by_keep)
53
+
54
+ def extra_repr(self):
55
+ return f'drop_prob={round(self.drop_prob,3):0.3f}'
56
+
57
+
58
+ class Mlp(nn.Module):
59
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
60
+ super().__init__()
61
+ out_features = out_features or in_features
62
+ hidden_features = hidden_features or in_features
63
+ self.fc1 = nn.Linear(in_features, hidden_features)
64
+ self.act = act_layer()
65
+ self.fc2 = nn.Linear(hidden_features, out_features)
66
+ self.drop = nn.Dropout(drop)
67
+
68
+ def forward(self, x):
69
+ x = self.fc1(x)
70
+ x = self.act(x)
71
+ x = self.drop(x)
72
+ x = self.fc2(x)
73
+ x = self.drop(x)
74
+ return x
75
+
76
+
77
+ def window_partition(x, window_size):
78
+ """
79
+ Args:
80
+ x: (B, L, C)
81
+ window_size (int): window size
82
+
83
+ Returns:
84
+ windows: (num_windows*B, window_size, C)
85
+ """
86
+ B, L, C = x.shape
87
+ x = x.view(B, L // window_size, window_size, C)
88
+ windows = x.permute(0, 1, 2, 3).contiguous().view(-1, window_size, C)
89
+ return windows
90
+
91
+
92
+ def window_reverse(windows, window_size, L):
93
+ """
94
+ Args:
95
+ windows: (num_windows*B, window_size, window_size, C)
96
+ window_size (int): Window size
97
+ L (int): sequence length
98
+
99
+ Returns:
100
+ x: (B, L, C)
101
+ """
102
+ B = int(windows.shape[0] / (L / window_size))
103
+ x = windows.view(B, L // window_size, window_size, -1)
104
+ x = x.permute(0, 1, 2, 3).contiguous().view(B, L, -1)
105
+ return x
106
+
107
+
108
+ # class WindowAttention_1D(nn.Module):
109
+ # r""" Window based multi-head self attention (W-MSA) module with relative position bias.
110
+ # It supports both of shifted and non-shifted window.
111
+ # Args:
112
+ # dim (int): Number of input channels.
113
+ # window_size (int): The height and width of the window.
114
+ # num_heads (int): Number of attention heads.
115
+ # qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
116
+ # attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
117
+ # proj_drop (float, optional): Dropout ratio of output. Default: 0.0
118
+ # pretrained_window_size (int): The height and width of the window in pre-training.
119
+ # """
120
+
121
+ # def __init__(self, dim, window_size, num_heads, qkv_bias=True, attn_drop=0., proj_drop=0.,
122
+ # pretrained_window_size=0):
123
+
124
+ # super().__init__()
125
+ # self.dim = dim
126
+ # self.window_size = window_size # Wl
127
+ # self.pretrained_window_size = pretrained_window_size
128
+ # self.num_heads = num_heads
129
+
130
+ # self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))), requires_grad=True)
131
+
132
+ # # mlp to generate continuous relative position bias
133
+ # self.cpb_mlp = nn.Sequential(nn.Linear(1, 512, bias=True),
134
+ # nn.ReLU(inplace=True),
135
+ # nn.Linear(512, num_heads, bias=False))
136
+
137
+ # # get relative_coords_table
138
+ # relative_coords_l = torch.arange(-(self.window_size - 1), self.window_size, dtype=torch.float32)
139
+ # relative_coords_table = torch.stack(
140
+ # torch.meshgrid([relative_coords_l], indexing='ij')).permute(1, 0).contiguous().unsqueeze(0) # 1, 2*Wl-1, 1
141
+ # if pretrained_window_size > 0:
142
+ # relative_coords_table[:, :, :] /= (pretrained_window_size - 1)
143
+ # else:
144
+ # relative_coords_table[:, :, :] /= (self.window_size - 1)
145
+ # relative_coords_table *= 8 # normalize to -8, 8
146
+ # relative_coords_table = torch.sign(relative_coords_table) * torch.log2(
147
+ # torch.abs(relative_coords_table) + 1.0) / np.log2(8)
148
+
149
+ # self.register_buffer("relative_coords_table", relative_coords_table)
150
+
151
+ # # get pair-wise relative position index for each token inside the window
152
+ # coords_l = torch.arange(self.window_size)
153
+ # coords = torch.stack(torch.meshgrid([coords_l], indexing='ij')) # 1, Wl
154
+ # coords_flatten = torch.flatten(coords, 1) # 1, Wl
155
+ # relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 1, Wl, Wl
156
+ # relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wl, Wl, 1
157
+ # relative_coords[:, :, 0] += self.window_size - 1 # shift to start from 0
158
+ # relative_position_index = relative_coords.sum(-1) # Wl, Wl
159
+ # self.register_buffer("relative_position_index", relative_position_index)
160
+
161
+ # self.qkv = nn.Linear(dim, dim * 3, bias=False)
162
+ # if qkv_bias:
163
+ # self.q_bias = nn.Parameter(torch.zeros(dim))
164
+ # self.v_bias = nn.Parameter(torch.zeros(dim))
165
+ # else:
166
+ # self.q_bias = None
167
+ # self.v_bias = None
168
+ # self.attn_drop = nn.Dropout(attn_drop)
169
+ # self.proj = nn.Linear(dim, dim)
170
+ # self.proj_drop = nn.Dropout(proj_drop)
171
+ # self.softmax = nn.Softmax(dim=-1)
172
+
173
+ # def forward(self, x, mask=None):
174
+ # """
175
+ # Args:
176
+ # x: input features with shape of (num_windows*B, N, C)
177
+ # mask: (0/-inf) mask with shape of (num_windows, Wl, Wl) or None
178
+ # """
179
+ # B_, N, C = x.shape
180
+ # qkv_bias = None
181
+ # if self.q_bias is not None:
182
+ # qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
183
+ # qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
184
+ # qkv = qkv.reshape(B_, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
185
+ # q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
186
+
187
+ # # cosine attention
188
+ # attn = (F.normalize(q, dim=-1) @ F.normalize(k, dim=-1).transpose(-2, -1))
189
+ # logit_scale = torch.clamp(self.logit_scale, max=torch.log(torch.tensor(1. / 0.01, device=attn.device))).exp()
190
+ # attn = attn * logit_scale
191
+
192
+ # relative_position_bias_table = self.cpb_mlp(self.relative_coords_table).view(-1, self.num_heads)
193
+ # relative_position_bias = relative_position_bias_table[self.relative_position_index.view(-1)].view(
194
+ # self.window_size, self.window_size, -1) # Wl,l,nH
195
+ # relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wl, Wl
196
+ # relative_position_bias = 16 * torch.sigmoid(relative_position_bias)
197
+ # attn = attn + relative_position_bias.unsqueeze(0)
198
+
199
+ # if mask is not None:
200
+ # nW = mask.shape[0]
201
+ # attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
202
+ # attn = attn.view(-1, self.num_heads, N, N)
203
+ # attn = self.softmax(attn)
204
+ # else:
205
+ # attn = self.softmax(attn)
206
+
207
+ # attn = self.attn_drop(attn)
208
+
209
+ # x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
210
+ # x = self.proj(x)
211
+ # x = self.proj_drop(x)
212
+ # return x
213
+
214
+ ###
215
+ class WindowAttention1D(nn.Module):
216
+ r""" Window based multi-head self attention (W-MSA) module with relative position bias.
217
+ It supports both of shifted and non-shifted window.
218
+
219
+ Args:
220
+ dim (int): Number of input channels.
221
+ window_size (int): The height and width of the window.
222
+ num_heads (int): Number of attention heads.
223
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
224
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
225
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
226
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
227
+ """
228
+
229
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
230
+
231
+ super().__init__()
232
+ self.dim = dim
233
+ self.window_size = window_size # Wl
234
+ self.num_heads = num_heads
235
+ head_dim = dim // num_heads
236
+ self.scale = qk_scale or head_dim ** -0.5
237
+
238
+ # define a parameter table of relative position bias
239
+ self.relative_position_bias_table = nn.Parameter(
240
+ torch.zeros((2 * window_size - 1), num_heads)) # 2*Ww-1, nH
241
+
242
+ # get pair-wise relative position index for each token inside the window
243
+ coords_l = torch.arange(self.window_size)
244
+ coords = torch.stack(torch.meshgrid(
245
+ [coords_l], indexing='ij')) # 1, Wl
246
+ coords_flatten = torch.flatten(coords, 1) # 1, Wl
247
+ relative_coords = coords_flatten[:, :, None] - \
248
+ coords_flatten[:, None, :] # 1, Wl, Wl
249
+ relative_coords = relative_coords.permute(
250
+ 1, 2, 0).contiguous() # Wl, Wl, 2
251
+ relative_coords[:, :, 0] += self.window_size - \
252
+ 1 # shift to start from 0
253
+ # relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
254
+ relative_position_index = relative_coords.sum(-1) # Wl, Wl
255
+ self.register_buffer("relative_position_index",
256
+ relative_position_index)
257
+
258
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
259
+ self.attn_drop = nn.Dropout(attn_drop)
260
+ self.proj = nn.Linear(dim, dim)
261
+ self.proj_drop = nn.Dropout(proj_drop)
262
+
263
+ trunc_normal_(self.relative_position_bias_table, std=.02)
264
+ self.softmax = nn.Softmax(dim=-1)
265
+
266
+ def forward(self, x, mask=None):
267
+ """
268
+ Args:
269
+ x: input features with shape of (num_windows*B, N, C)
270
+ mask: (0/-inf) mask with shape of (num_windows, Wl, Wl) or None
271
+ """
272
+ B_, N, C = x.shape
273
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C //
274
+ self.num_heads).permute(2, 0, 3, 1, 4)
275
+ # make torchscript happy (cannot use tensor as tuple)
276
+ q, k, v = qkv[0], qkv[1], qkv[2]
277
+
278
+ q = q * self.scale
279
+ attn = (q @ k.transpose(-2, -1))
280
+
281
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
282
+ self.window_size, self.window_size, -1) # Wl,Wl,nH
283
+ relative_position_bias = relative_position_bias.permute(
284
+ 2, 0, 1).contiguous() # nH, Wl, Wl
285
+ attn = attn + relative_position_bias.unsqueeze(0)
286
+
287
+ if mask is not None:
288
+ nW = mask.shape[0]
289
+ attn = attn.view(B_ // nW, nW, self.num_heads, N,
290
+ N) + mask.unsqueeze(1).unsqueeze(0)
291
+ attn = attn.view(-1, self.num_heads, N, N)
292
+ attn = self.softmax(attn)
293
+ else:
294
+ attn = self.softmax(attn)
295
+
296
+ attn = self.attn_drop(attn)
297
+
298
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
299
+ x = self.proj(x)
300
+ x = self.proj_drop(x)
301
+ return x
302
+ ###
303
+
304
+ def compute_mask(L, window_size, shift_size):
305
+ Lp = int(np.ceil(L / window_size)) * window_size
306
+ img_mask = torch.zeros((1, Lp, 1)) # 1 Lp 1
307
+ pad_size = int(Lp - L)
308
+ if (pad_size == 0) or (pad_size + shift_size == window_size):
309
+ segs = (slice(-window_size), slice(-window_size, -shift_size), slice(-shift_size, None))
310
+ elif pad_size + shift_size > window_size:
311
+ seg1 = int(window_size * 2 - L + shift_size)
312
+ segs = (
313
+ slice(-seg1), slice(-seg1, -window_size), slice(-window_size, -shift_size), slice(-shift_size, None))
314
+ elif pad_size + shift_size < window_size:
315
+ seg1 = int(window_size * 2 - L + shift_size)
316
+ segs = (
317
+ slice(-window_size), slice(-window_size, -seg1), slice(-seg1, -shift_size), slice(-shift_size, None))
318
+ cnt = 0
319
+ for d in segs:
320
+ img_mask[:, d, :] = cnt
321
+ cnt += 1
322
+ mask_windows = window_partition(img_mask, window_size) # nW, ws, 1
323
+ mask_windows = mask_windows.squeeze(-1) # nW, ws
324
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
325
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
326
+ return attn_mask
327
+
328
+
329
+ class SwinTransformerBlock_1D(nn.Module):
330
+ r""" Swin Transformer Block.
331
+ Args:
332
+ dim (int): Number of input channels.
333
+ input_resolution (int): Input resulotion.
334
+ num_heads (int): Number of attention heads.
335
+ window_size (int): Window size.
336
+ shift_size (int): Shift size for SW-MSA.
337
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
338
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
339
+ drop (float, optional): Dropout rate. Default: 0.0
340
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
341
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
342
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
343
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
344
+ pretrained_window_size (int): Window size in pre-training.
345
+ """
346
+
347
+ def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0,
348
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
349
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm, pretrained_window_size=0):
350
+ super().__init__()
351
+ self.dim = dim
352
+ self.input_resolution = input_resolution
353
+ self.num_heads = num_heads
354
+ self.window_size = window_size
355
+ self.shift_size = shift_size
356
+ self.mlp_ratio = mlp_ratio
357
+ if self.input_resolution <= self.window_size:
358
+ # if window size is larger than input resolution, we don't partition windows
359
+ self.shift_size = 0
360
+ self.window_size = self.input_resolution
361
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
362
+
363
+ self.norm1 = norm_layer(dim)
364
+ # self.attn = WindowAttention_1D(
365
+ # dim, window_size=self.window_size, num_heads=num_heads,
366
+ # qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop,
367
+ # pretrained_window_size=pretrained_window_size)
368
+ self.attn = WindowAttention1D(
369
+ dim, window_size=self.window_size, num_heads=num_heads,
370
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
371
+
372
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
373
+ self.norm2 = norm_layer(dim)
374
+ mlp_hidden_dim = int(dim * mlp_ratio)
375
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
376
+
377
+ if self.shift_size > 0:
378
+ # calculate attention mask for SW-MSA
379
+ L = self.input_resolution
380
+ attn_mask = compute_mask(L, self.window_size, self.shift_size)
381
+ else:
382
+ attn_mask = None
383
+
384
+ self.register_buffer("attn_mask", attn_mask)
385
+
386
+ def forward(self, x):
387
+ Li = self.input_resolution
388
+ B, L, C = x.shape
389
+ assert L == Li, "input feature has wrong size"
390
+
391
+ shortcut = x
392
+ # x = x.view(B, L, C)
393
+
394
+ # padding x
395
+ pad_r = (self.window_size - L % self.window_size) % self.window_size
396
+ x = F.pad(x, (0, 0, 0, pad_r))
397
+ _, Lp, _ = x.shape
398
+
399
+ # cyclic shift
400
+ if self.shift_size > 0:
401
+ shifted_x = torch.roll(x, shifts=(-self.shift_size), dims=(1))
402
+ else:
403
+ shifted_x = x
404
+
405
+ # partition windows
406
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, C
407
+ x_windows = x_windows.view(-1, self.window_size, C) # nW*B, window_siz, C
408
+
409
+ # W-MSA/SW-MSA
410
+ attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size, C
411
+
412
+ # merge windows
413
+ attn_windows = attn_windows.view(-1, self.window_size, C)
414
+ shifted_x = window_reverse(attn_windows, self.window_size, Lp) # B L' C
415
+
416
+ # reverse cyclic shift
417
+ if self.shift_size > 0:
418
+ x = torch.roll(shifted_x, shifts=(self.shift_size), dims=(1))
419
+ else:
420
+ x = shifted_x
421
+ x = x.view(B, Lp, C)
422
+ # reverse padding x
423
+ x = x[:, :L, :].contiguous()
424
+ x = shortcut + self.drop_path(self.norm1(x))
425
+
426
+ # FFN
427
+ x = x + self.drop_path(self.norm2(self.mlp(x)))
428
+
429
+ return x
430
+
431
+
432
+ class PatchMerging(nn.Module):
433
+ """ Patch Merging Layer
434
+
435
+ Args:
436
+ dim (int): Number of input channels.
437
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
438
+ """
439
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
440
+ super().__init__()
441
+ self.dim = dim
442
+ self.reduction = nn.Linear(2 * dim, 2 * dim, bias=False)
443
+ self.norm = norm_layer(2 * dim)
444
+
445
+ def forward(self, x):
446
+ """ Forward function.
447
+
448
+ Args:
449
+ x: Input feature, tensor size (B, L, C).
450
+ """
451
+ B, L, C = x.shape
452
+
453
+ # padding
454
+ # pad_input = (L % 2 == 1)
455
+ # if pad_input:
456
+ # x = F.pad(x, (0, 0, 0, L % 2))
457
+ x = F.pad(x, (0, 0, 0, L % 2))
458
+
459
+ x0 = x[:, 0::2, :] # B L/2 C
460
+ x1 = x[:, 1::2, :] # B L/2 C
461
+ x = torch.cat([x0, x1], -1) # B L/2 2*C
462
+
463
+ x = self.norm(x)
464
+ x = self.reduction(x)
465
+
466
+ return x
467
+
468
+
469
+ class BasicLayer(nn.Module):
470
+ """ A basic Swin Transformer layer for one stage.
471
+ Args:
472
+ dim (int): Number of input channels.
473
+ input_resolution (int): Input resolution.
474
+ depth (int): Number of blocks.
475
+ num_heads (int): Number of attention heads.
476
+ window_size (int): Local window size.
477
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
478
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
479
+ drop (float, optional): Dropout rate. Default: 0.0
480
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
481
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
482
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
483
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
484
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
485
+ pretrained_window_size (int): Local window size in pre-training.
486
+ """
487
+
488
+ def __init__(self, dim, input_resolution, depth, num_heads, window_size,
489
+ mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0.,
490
+ drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False,
491
+ pretrained_window_size=0):
492
+
493
+ super().__init__()
494
+ self.dim = dim
495
+ self.input_resolution = input_resolution
496
+ self.depth = depth
497
+ self.use_checkpoint = use_checkpoint
498
+
499
+ # build blocks
500
+ self.blocks = nn.ModuleList([
501
+ SwinTransformerBlock_1D(dim=dim, input_resolution=input_resolution,
502
+ num_heads=num_heads, window_size=window_size,
503
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
504
+ mlp_ratio=mlp_ratio,
505
+ qkv_bias=qkv_bias,
506
+ drop=drop, attn_drop=attn_drop,
507
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
508
+ norm_layer=norm_layer,
509
+ pretrained_window_size=pretrained_window_size)
510
+ for i in range(depth)])
511
+
512
+ # patch merging layer
513
+ if downsample is not None:
514
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
515
+ else:
516
+ self.downsample = None
517
+
518
+ def forward(self, x):
519
+ for blk in self.blocks:
520
+ if self.use_checkpoint:
521
+ x = checkpoint.checkpoint(blk, x)
522
+ else:
523
+ x = blk(x)
524
+ if self.downsample is not None:
525
+ x = self.downsample(x)
526
+ return x
527
+
528
+ def _init_respostnorm(self):
529
+ for blk in self.blocks:
530
+ nn.init.constant_(blk.norm1.bias, 0)
531
+ nn.init.constant_(blk.norm1.weight, 0)
532
+ nn.init.constant_(blk.norm2.bias, 0)
533
+ nn.init.constant_(blk.norm2.weight, 0)
534
+
535
+
536
+ class PatchEmbed1D(nn.Module):
537
+ """ Video to Patch Embedding.
538
+
539
+ Args:
540
+ seq_len (int): Sequence length.
541
+ patch_size (int): Patch token size. Default: 4.
542
+ in_chans (int): Number of input video channels. Default: 3.
543
+ embed_dim (int): Number of linear projection output channels. Default: 96.
544
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
545
+ """
546
+ def __init__(self, seq_len, patch_size=4, in_chans=32, embed_dim=128, norm_layer=None):
547
+ super().__init__()
548
+ self.patch_size = patch_size
549
+
550
+ self.in_chans = in_chans
551
+ self.embed_dim = embed_dim
552
+
553
+ self.proj = nn.Conv1d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
554
+ self.num_patches = math.ceil(seq_len / patch_size)
555
+ self.patches_resolution = math.ceil(seq_len / patch_size)
556
+ if norm_layer is not None:
557
+ self.norm = norm_layer(embed_dim)
558
+ else:
559
+ self.norm = None
560
+
561
+ def forward(self, x):
562
+ """Forward function."""
563
+ # padding
564
+ _, _, L = x.size()
565
+ pad_r = (self.patch_size - L % self.patch_size) % self.patch_size
566
+ x = F.pad(x, (0, pad_r))
567
+ x = self.proj(x) # B C Wl
568
+ if self.norm is not None:
569
+ # Wl = x.size(2)
570
+ x = x.transpose(1, 2)
571
+ x = self.norm(x)
572
+ # x = x.transpose(1, 2).view(-1, self.embed_dim, Wl)
573
+
574
+ return x
575
+
576
+
577
+ class SwinTransformer_1D(nn.Module):
578
+ r""" Swin Transformer
579
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
580
+ https://arxiv.org/pdf/2103.14030
581
+ Args:
582
+ img_size (int | tuple(int)): Input image size. Default 224
583
+ patch_size (int | tuple(int)): Patch size. Default: 4
584
+ in_chans (int): Number of input image channels. Default: 3
585
+ num_classes (int): Number of classes for classification head. Default: 1000
586
+ embed_dim (int): Patch embedding dimension. Default: 96
587
+ depths (tuple(int)): Depth of each Swin Transformer layer.
588
+ num_heads (tuple(int)): Number of attention heads in different layers.
589
+ window_size (int): Window size. Default: 7
590
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
591
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
592
+ drop_rate (float): Dropout rate. Default: 0
593
+ attn_drop_rate (float): Attention dropout rate. Default: 0
594
+ drop_path_rate (float): Stochastic depth rate. Default: 0.1
595
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
596
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
597
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True
598
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
599
+ pretrained_window_sizes (tuple(int)): Pretrained window sizes of each layer.
600
+ """
601
+
602
+ def __init__(self, seq_len=500, patch_size=4, in_chans=32, num_classes=4,
603
+ embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24],
604
+ window_size=7, mlp_ratio=4., qkv_bias=True,
605
+ drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
606
+ norm_layer=nn.LayerNorm, ape=False, patch_norm=True,
607
+ use_checkpoint=False, pretrained_window_sizes=[0, 0, 0, 0], **kwargs):
608
+ super().__init__()
609
+
610
+ self.num_classes = num_classes
611
+ self.num_layers = len(depths)
612
+ self.embed_dim = embed_dim
613
+ self.ape = ape
614
+ self.patch_norm = patch_norm
615
+ self.num_features = int(embed_dim * 2 ** (self.num_layers - 1))
616
+ self.mlp_ratio = mlp_ratio
617
+
618
+ # split image into non-overlapping patches
619
+ self.patch_embed = PatchEmbed1D(seq_len=seq_len,
620
+ patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,
621
+ norm_layer=norm_layer if self.patch_norm else None)
622
+ num_patches = self.patch_embed.num_patches
623
+ patches_resolution = self.patch_embed.patches_resolution
624
+ self.patches_resolution = patches_resolution
625
+
626
+ # absolute position embedding
627
+ if self.ape:
628
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
629
+ trunc_normal_(self.absolute_pos_embed, std=.02)
630
+
631
+ self.pos_drop = nn.Dropout(p=drop_rate)
632
+
633
+ # stochastic depth
634
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
635
+
636
+ # build layers
637
+ self.layers = nn.ModuleList()
638
+ for i_layer in range(self.num_layers):
639
+ layer = BasicLayer(dim=int(embed_dim * 2 ** i_layer),
640
+ input_resolution=math.ceil(patches_resolution / (2 ** i_layer)),
641
+ depth=depths[i_layer],
642
+ num_heads=num_heads[i_layer],
643
+ window_size=window_size,
644
+ mlp_ratio=self.mlp_ratio,
645
+ qkv_bias=qkv_bias,
646
+ drop=drop_rate, attn_drop=attn_drop_rate,
647
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
648
+ norm_layer=norm_layer,
649
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
650
+ use_checkpoint=use_checkpoint,
651
+ pretrained_window_size=pretrained_window_sizes[i_layer])
652
+ self.layers.append(layer)
653
+
654
+ self.norm = norm_layer(self.num_features)
655
+ self.avgpool = nn.AdaptiveAvgPool1d(1)
656
+
657
+ self.head = nn.Linear(self.num_features + 1024, num_classes) if num_classes > 0 else nn.Identity()
658
+ self.apply(self._init_weights)
659
+ for bly in self.layers:
660
+ bly._init_respostnorm()
661
+
662
+ def _init_weights(self, m):
663
+ if isinstance(m, nn.Linear):
664
+ trunc_normal_(m.weight, std=.02)
665
+ if isinstance(m, nn.Linear) and m.bias is not None:
666
+ nn.init.constant_(m.bias, 0)
667
+ elif isinstance(m, nn.LayerNorm):
668
+ nn.init.constant_(m.bias, 0)
669
+ nn.init.constant_(m.weight, 1.0)
670
+
671
+ @torch.jit.ignore
672
+ def no_weight_decay(self):
673
+ return {'absolute_pos_embed'}
674
+
675
+ @torch.jit.ignore
676
+ def no_weight_decay_keywords(self):
677
+ return {"cpb_mlp", "logit_scale", 'relative_position_bias_table'}
678
+
679
+ def forward_features(self, x):
680
+ x = self.patch_embed(x)
681
+ if self.ape:
682
+ x = x + self.absolute_pos_embed
683
+ x = self.pos_drop(x)
684
+
685
+ for layer in self.layers:
686
+ x = layer(x)
687
+
688
+ x = self.norm(x) # B L C
689
+ x = self.avgpool(x.transpose(1, 2)) # B C 1
690
+ x = torch.flatten(x, 1)
691
+ return x
692
+
693
+ # def forward(self, x):
694
+ # x = self.forward_features(x)
695
+ # x = self.head(x)
696
+ # return x
697
+
698
+ def forward(self, x, additional_input):
699
+ # Process x through Swin Transformer
700
+ x = self.forward_features(x)
701
+
702
+ additional_input = additional_input.view(additional_input.size(0), -1)
703
+
704
+ x = torch.cat((x, additional_input), dim=1)
705
+
706
+ x = self.head(x)
707
+
708
+ return x
709
+
710
+
711
+ if __name__ == "__main__":
712
+ net = SwinTransformerV2_1D(seq_len=2000, patch_size=4, in_chans=32, num_classes=9,
713
+ embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24],
714
+ window_size=31, mlp_ratio=4., qkv_bias=True,
715
+ drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
716
+ norm_layer=nn.LayerNorm, ape=False, patch_norm=True,
717
+ use_checkpoint=False, pretrained_window_sizes=[0, 0, 0, 0])
718
+ x = torch.rand(2, 32, 2000)
719
+ # x = torch.rand(2, 96, 64)
720
+ print(net(x).shape)
tools/precompute_demo.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tạo dữ liệu "chuyến mẫu" cho web (chạy 1 lần trên máy, rồi upload lên dataset PRIVATE trên Hugging Face).
3
+
4
+ Dùng lại đúng các hàm của web (inference.load_sensors, video_pipeline.*) để cửa sổ, đồng bộ
5
+ và frame khớp tuyệt đối với lúc web chạy. Phần tốn thời gian nhất (DINOv3 trên ~14k frame)
6
+ được tính sẵn ở đây; khi bấm "Phân tích chuyến mẫu", web vẫn chạy thật Temporal Transformer,
7
+ nhánh video và fusion trên các đặc trưng này.
8
+
9
+ Usage (từ thư mục web/):
10
+ python tools/precompute_demo.py --trip "<thư mục chuyến UAH>" --out demo
11
+ Kết quả trong demo/: RAW_ACCELEROMETERS.txt, RAW_GPS.txt, cache.npz, thumbs.json, meta.json
12
+ """
13
+
14
+ import argparse
15
+ import glob
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import sys
21
+ import tempfile
22
+ import time
23
+
24
+ import numpy as np
25
+
26
+ HERE = os.path.dirname(os.path.abspath(__file__))
27
+ sys.path.insert(0, os.path.dirname(HERE))
28
+
29
+ import inference as inf # noqa: E402
30
+ import video_pipeline as vp # noqa: E402
31
+
32
+ try:
33
+ sys.stdout.reconfigure(errors='backslashreplace')
34
+ except AttributeError:
35
+ pass
36
+
37
+ TRIP_RE = re.compile(r'(\d{14})-(\d+)km-(D\d)-(NORMAL|AGGRESSIVE|DROWSY)(\d?)-(MOTORWAY|SECONDARY)')
38
+ LABEL_VI = {'NORMAL': 'Bình thường', 'AGGRESSIVE': 'Lái xe hung hăng', 'DROWSY': 'Dấu hiệu buồn ngủ'}
39
+ ROAD_VI = {'MOTORWAY': 'cao tốc', 'SECONDARY': 'đường thường'}
40
+
41
+
42
+ def main():
43
+ p = argparse.ArgumentParser()
44
+ p.add_argument('--trip', required=True, help='thư mục 1 chuyến UAH (chứa .mp4, RAW_ACCELEROMETERS.txt, RAW_GPS.txt)')
45
+ p.add_argument('--out', default=os.path.join(os.path.dirname(HERE), 'demo'))
46
+ p.add_argument('--weights', default=os.path.join(os.path.dirname(HERE), 'weights'))
47
+ args = p.parse_args()
48
+
49
+ trip = os.path.normpath(args.trip)
50
+ name = os.path.basename(trip)
51
+ mp4 = glob.glob(os.path.join(trip, '*.mp4'))
52
+ assert len(mp4) == 1, f'cần đúng 1 file .mp4 trong {trip}'
53
+ mp4 = mp4[0]
54
+ t0 = time.time()
55
+ log = lambda m: print(f'[{time.time() - t0:6.0f}s] {m}', flush=True)
56
+
57
+ acc_b = open(os.path.join(trip, 'RAW_ACCELEROMETERS.txt'), 'rb').read()
58
+ gps_b = open(os.path.join(trip, 'RAW_GPS.txt'), 'rb').read()
59
+ sens = inf.load_sensors(acc_b, gps_b)
60
+ analyzer = inf.Analyzer(args.weights)
61
+ assert analyzer.video is not None, 'thiếu weights/video_3d.pth'
62
+
63
+ log('Đồng bộ video…')
64
+ fps, frame_times, flow_t, flow_x = vp.scan_video(mp4)
65
+ base = vp.name_offset(name, os.path.basename(mp4))
66
+ sync = vp.verify_offset(base, flow_t, flow_x, sens['acc'], sens['gps'])
67
+ log(f'sync: {sync}')
68
+ assert sync['verified'], 'chuyến này không kiểm chứng được đồng bộ, hãy chọn chuyến khác'
69
+ plans = vp.plan_frames(sens['windows'], sens['acc'], sync['offset'], frame_times, fps)
70
+
71
+ with tempfile.TemporaryDirectory() as tmp:
72
+ fpath = os.path.join(tmp, 'frames.npy')
73
+ log(f'Lấy frame cho {len(plans)} đoạn…')
74
+ complete, thumbs = vp.extract_frames(mp4, plans, fpath, log)
75
+ rows = [i for i, ok in enumerate(complete) if ok]
76
+ log(f'DINOv3 (CPU) cho {len(rows)} đoạn…')
77
+ cls = vp.backbone_cls(analyzer.video, fpath, rows, device='cpu', progress=log)
78
+
79
+ os.makedirs(args.out, exist_ok=True)
80
+ t_start = np.array([sens['windows'][plans[r][0]]['t_start'] for r in rows])
81
+ np.savez_compressed(os.path.join(args.out, 'cache.npz'), t_start=t_start, cls=cls)
82
+ json.dump([thumbs[r] for r in rows], open(os.path.join(args.out, 'thumbs.json'), 'w', encoding='utf-8'))
83
+ shutil.copy2(os.path.join(trip, 'RAW_ACCELEROMETERS.txt'), args.out)
84
+ shutil.copy2(os.path.join(trip, 'RAW_GPS.txt'), args.out)
85
+
86
+ m = TRIP_RE.search(name)
87
+ meta = dict(trip_name=name, offset=sync['offset'],
88
+ sync={k: v for k, v in sync.items() if k != 'reason'},
89
+ windows=len(rows), duration=float(sens['acc'][-1, 0] - sens['acc'][0, 0]))
90
+ if m:
91
+ _, km, drv, beh, _, road = m.groups()
92
+ meta.update(driver=drv, behavior=beh, road=road, km=int(km),
93
+ title=f'Tài xế {drv} · {ROAD_VI[road]} · {km} km',
94
+ reference=LABEL_VI[beh])
95
+ json.dump(meta, open(os.path.join(args.out, 'meta.json'), 'w', encoding='utf-8'), ensure_ascii=False, indent=2)
96
+ log(f'Xong: {args.out} ({len(rows)} đoạn)')
97
+
98
+
99
+ if __name__ == '__main__':
100
+ main()
video_pipeline.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Nhánh video cho web: đồng bộ video <-> cảm biến, lấy 77 frame cho mỗi đoạn 5 giây,
3
+ chạy DINOv3 (backbone) để lấy CLS token từng frame, tạo ảnh thu nhỏ để hiển thị.
4
+
5
+ Các bước giống hệt lúc tạo dữ liệu train (dust_dinov3/prepare_uah_data.py):
6
+ - đồng bộ: tương quan optical flow ngang của video với yaw rate (dự phòng: hướng GPS),
7
+ chỉ chấp nhận offset có đỉnh tương quan rõ và khớp giữa quét gần và quét rộng;
8
+ - frame: 77 thời điểm trải đều trên khoảng thời gian thật của 51 mẫu gia tốc, lấy frame
9
+ gần nhất (lệch <= nửa chu kỳ frame), cắt vuông giữa, 224x224, RGB, chuẩn hoá ImageNet.
10
+ """
11
+
12
+ import base64
13
+ import datetime as dt
14
+ import os
15
+ import re
16
+
17
+ import cv2
18
+ import numpy as np
19
+ import torch
20
+
21
+ SYNC_FS = 5.0
22
+ NUM_FRAMES = 77
23
+ SIZE = 224
24
+ THUMB_W, THUMB_H = 288, 162
25
+ IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
26
+ IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
27
+ TS_RE = re.compile(r'(\d{14})')
28
+
29
+
30
+ # ----------------------------------------------------------------------------
31
+ # Thông tin video
32
+ # ----------------------------------------------------------------------------
33
+ def probe_video(path):
34
+ """Mở thử video. Trả về (fps, số frame, thời lượng giây) hoặc ném ValueError."""
35
+ cap = cv2.VideoCapture(path)
36
+ if not cap.isOpened():
37
+ raise ValueError('Không mở được video. File có thể hỏng hoặc không phải video.')
38
+ fps = cap.get(cv2.CAP_PROP_FPS)
39
+ n = cap.get(cv2.CAP_PROP_FRAME_COUNT)
40
+ ok, _ = cap.read()
41
+ cap.release()
42
+ if not ok or fps <= 0 or n <= 0:
43
+ raise ValueError('Video không đọc được frame nào.')
44
+ return float(fps), int(n), float(n / fps)
45
+
46
+
47
+ def name_offset(trip_name, video_name):
48
+ """Offset theo tên file kiểu UAH (route_start - video_start, giây). None nếu không suy ra được."""
49
+ a = TS_RE.search(trip_name or '')
50
+ b = TS_RE.search(video_name or '')
51
+ if not (a and b):
52
+ return None
53
+ try:
54
+ ta = dt.datetime.strptime(a.group(1), '%Y%m%d%H%M%S')
55
+ tb = dt.datetime.strptime(b.group(1), '%Y%m%d%H%M%S')
56
+ except ValueError:
57
+ return None
58
+ return (ta - tb).total_seconds()
59
+
60
+
61
+ # ----------------------------------------------------------------------------
62
+ # Đồng bộ
63
+ # ----------------------------------------------------------------------------
64
+ def scan_video(path, progress=None):
65
+ """1 lượt giải mã: timestamp mọi frame + tín hiệu optical flow ngang ở SYNC_FS Hz."""
66
+ cap = cv2.VideoCapture(path)
67
+ fps = cap.get(cv2.CAP_PROP_FPS)
68
+ total = max(1, int(cap.get(cv2.CAP_PROP_FRAME_COUNT)))
69
+ frame_times, flow_t, flow_x = [], [], []
70
+ prev, next_t = None, 0.0
71
+ while True:
72
+ if not cap.grab():
73
+ break
74
+ t = cap.get(cv2.CAP_PROP_POS_MSEC) / 1000.0
75
+ frame_times.append(t)
76
+ if progress and len(frame_times) % 3000 == 0:
77
+ progress(f'Đang đọc video để đồng bộ: {100 * len(frame_times) // total}%')
78
+ if t + 1e-6 < next_t:
79
+ continue
80
+ ok, f = cap.retrieve()
81
+ if not ok:
82
+ break
83
+ next_t = t + 1.0 / SYNC_FS
84
+ g = cv2.cvtColor(cv2.resize(f, (320, 180), interpolation=cv2.INTER_AREA), cv2.COLOR_BGR2GRAY)
85
+ g = g[54:100, 16:256] # dải chân trời, bỏ A-pillar bên phải
86
+ if prev is not None:
87
+ flow = cv2.calcOpticalFlowFarneback(prev, g, None, 0.5, 3, 15, 3, 5, 1.2, 0)
88
+ flow_t.append(t)
89
+ flow_x.append(float(np.median(flow[..., 0])))
90
+ prev = g
91
+ cap.release()
92
+ return fps, np.asarray(frame_times), np.asarray(flow_t), np.asarray(flow_x)
93
+
94
+
95
+ def _band(x, short=1.0, long=30.0):
96
+ def ma(y, sec):
97
+ n = max(1, int(round(sec * SYNC_FS)))
98
+ return np.convolve(y, np.ones(n) / n, mode='same')
99
+ y = ma(x, short)
100
+ return y - ma(y, long)
101
+
102
+
103
+ def _reference_signals(acc, gps):
104
+ refs = [('yaw_rate', acc[:, 0], np.gradient(np.unwrap(acc[:, 10]), acc[:, 0]))]
105
+ if gps is not None and len(gps) > 30:
106
+ tg = gps[:, 0]
107
+ rate = -np.gradient(np.unwrap(np.deg2rad(gps[:, 7])), tg)
108
+ rate[gps[:, 1] < 10] = 0.0
109
+ refs.append(('gps_course_rate', tg, rate))
110
+ return refs
111
+
112
+
113
+ def _corr_scan(flow_t, flow_x, ref_t, ref_x, lags, min_overlap):
114
+ g0 = np.ceil(ref_t[0])
115
+ grid = np.arange(g0, ref_t[-1], 1 / SYNC_FS)
116
+ s = _band(np.interp(grid, ref_t, ref_x))
117
+ vgrid = np.arange(0, flow_t[-1], 1 / SYNC_FS)
118
+ v = _band(np.interp(vgrid, flow_t, np.clip(flow_x, -10, 10)))
119
+ need = max(min_overlap * len(grid), 60 * SYNC_FS)
120
+ out = np.full(len(lags), np.nan)
121
+ for i, L in enumerate(lags):
122
+ k = int(round((g0 + L) * SYNC_FS))
123
+ i0, i1 = max(0, -k), min(len(s), len(v) - k)
124
+ if i1 - i0 < need:
125
+ continue
126
+ a = v[i0 + k:i1 + k] - v[i0 + k:i1 + k].mean()
127
+ b = s[i0:i1] - s[i0:i1].mean()
128
+ den = np.sqrt((a * a).sum() * (b * b).sum())
129
+ if den > 0:
130
+ out[i] = (a * b).sum() / den
131
+ return out
132
+
133
+
134
+ def _peak(lags, corr, exclude_sec=10.0):
135
+ c = np.nan_to_num(corr, nan=-np.inf)
136
+ i = int(np.argmax(c))
137
+ far = np.abs(lags - lags[i]) > exclude_sec
138
+ second = float(np.nanmax(np.where(far, np.nan_to_num(np.abs(corr), nan=0), np.nan))) if far.any() else 0.0
139
+ return float(lags[i]), float(corr[i]), second
140
+
141
+
142
+ def verify_offset(base_offset, flow_t, flow_x, acc, gps, search=10.0, min_corr=0.15, min_ratio=1.5):
143
+ """Kiểm chứng offset. base_offset=None (không có tên file kiểu UAH) -> lấy đỉnh của quét rộng
144
+ làm offset gốc, sau đó vẫn phải qua kiểm tra quét gần như bình thường."""
145
+ if len(flow_t) < 60 * SYNC_FS:
146
+ return dict(verified=False, reason='video quá ngắn để đồng bộ')
147
+ step = 0.2
148
+ wide = np.arange(-flow_t[-1], flow_t[-1] + 1e-9, step)
149
+ res = dict(verified=False, name_offset=base_offset)
150
+ for ref, rt, rx in _reference_signals(acc, gps):
151
+ lag_w, corr_w, second_w = _peak(wide, _corr_scan(flow_t, flow_x, rt, rx, wide, 0.5))
152
+ base = lag_w if base_offset is None else base_offset
153
+ near = np.arange(base - search, base + search + 1e-9, step)
154
+ lag_n, corr_n, second_n = _peak(near, _corr_scan(flow_t, flow_x, rt, rx, near, 0.0))
155
+ ratio = corr_n / max(second_n, 1e-6)
156
+ ok = corr_n >= min_corr and ratio >= min_ratio and abs(lag_w - lag_n) <= 2.0
157
+ res.update(ref=ref, offset=lag_n, corr=corr_n, ratio=ratio, wide_lag=lag_w, verified=bool(ok))
158
+ if ok:
159
+ break
160
+ if not res['verified']:
161
+ res['reason'] = 'không tìm được độ lệch thời gian đáng tin giữa video và cảm biến'
162
+ return res
163
+
164
+
165
+ # ----------------------------------------------------------------------------
166
+ # Lấy frame
167
+ # ----------------------------------------------------------------------------
168
+ def plan_frames(windows, acc, offset, frame_times, fps, kine_len=51):
169
+ """Với mỗi cửa sổ hợp lệ, chọn chỉ số 77 frame thật gần nhất. Trả về list (window_index, idx)."""
170
+ half = 0.5 / fps + 0.005
171
+ plans = []
172
+ for wi, w in enumerate(windows):
173
+ if not w['valid']:
174
+ continue
175
+ ts = acc[w['i0']:w['i0'] + kine_len, 0]
176
+ targets = np.linspace(ts[0], ts[-1], NUM_FRAMES) + offset
177
+ if targets[0] < frame_times[0] or targets[-1] > frame_times[-1]:
178
+ continue
179
+ idx = np.clip(np.searchsorted(frame_times, targets), 1, len(frame_times) - 1)
180
+ left = (targets - frame_times[idx - 1]) <= (frame_times[idx] - targets)
181
+ idx = np.where(left, idx - 1, idx)
182
+ if np.abs(frame_times[idx] - targets).max() > half:
183
+ continue
184
+ lo, hi = idx.min(), idx.max()
185
+ if np.diff(frame_times[lo:hi + 1]).max() > 3.0 / fps:
186
+ continue
187
+ plans.append((wi, idx))
188
+ return plans
189
+
190
+
191
+ def _prep(f):
192
+ h, w = f.shape[:2]
193
+ s = min(h, w)
194
+ y0, x0 = (h - s) // 2, (w - s) // 2
195
+ f = cv2.resize(f[y0:y0 + s, x0:x0 + s], (SIZE, SIZE), interpolation=cv2.INTER_AREA)
196
+ return cv2.cvtColor(f, cv2.COLOR_BGR2RGB)
197
+
198
+
199
+ def _thumb(f):
200
+ t = cv2.resize(f, (THUMB_W, THUMB_H), interpolation=cv2.INTER_AREA)
201
+ ok, buf = cv2.imencode('.jpg', t, [cv2.IMWRITE_JPEG_QUALITY, 70])
202
+ return base64.b64encode(buf.tobytes()).decode('ascii') if ok else None
203
+
204
+
205
+ def extract_frames(path, plans, frames_path, progress=None):
206
+ """Giải mã tuần tự, ghi frame 224x224 uint8 của mọi cửa sổ vào memmap (N, 77, 224, 224, 3)
207
+ và tạo ảnh thu nhỏ (frame giữa mỗi cửa sổ). Trả về (danh sách cửa sổ đủ frame, thumbs)."""
208
+ n = len(plans)
209
+ mm = np.lib.format.open_memmap(frames_path, mode='w+', dtype=np.uint8, shape=(n, NUM_FRAMES, SIZE, SIZE, 3))
210
+ need = {}
211
+ for pi, (_, idx) in enumerate(plans):
212
+ for k, fi in enumerate(idx):
213
+ need.setdefault(int(fi), []).append((pi, k))
214
+ filled = np.zeros((n, NUM_FRAMES), dtype=bool)
215
+ thumbs = [None] * n
216
+ mid = NUM_FRAMES // 2
217
+ order = sorted(need)
218
+ cap = cv2.VideoCapture(path)
219
+ fi, j = -1, 0
220
+ while j < len(order):
221
+ if not cap.grab():
222
+ break
223
+ fi += 1
224
+ if fi != order[j]:
225
+ continue
226
+ ok, f = cap.retrieve()
227
+ if ok:
228
+ img = _prep(f)
229
+ for pi, k in need[fi]:
230
+ mm[pi, k] = img
231
+ filled[pi, k] = True
232
+ if k == mid:
233
+ thumbs[pi] = _thumb(f)
234
+ j += 1
235
+ if progress and j % 2000 == 0:
236
+ progress(f'Đang lấy frame video: {100 * j // len(order)}%')
237
+ cap.release()
238
+ mm.flush()
239
+ del mm
240
+ complete = [bool(filled[pi].all()) for pi in range(n)]
241
+ return complete, thumbs
242
+
243
+
244
+ @torch.no_grad()
245
+ def backbone_cls(encoder, frames_path, rows, device='cpu', batch_frames=256, progress=None):
246
+ """CLS token DINOv3 cho các cửa sổ `rows` trong memmap frame. Trả về float16 (len(rows), 77, 384)."""
247
+ mm = np.load(frames_path, mmap_mode='r')
248
+ enc = encoder.to(device).eval()
249
+ mean = torch.tensor(IMAGENET_MEAN, device=device).view(1, 3, 1, 1)
250
+ std = torch.tensor(IMAGENET_STD, device=device).view(1, 3, 1, 1)
251
+ out = np.zeros((len(rows), NUM_FRAMES, enc.hidden_size), dtype=np.float16)
252
+ use_amp = device != 'cpu'
253
+ for r, row in enumerate(rows):
254
+ x = torch.from_numpy(np.ascontiguousarray(mm[row])).to(device) # (77, 224, 224, 3) uint8
255
+ x = x.permute(0, 3, 1, 2).float().div_(255.0).sub_(mean).div_(std) # (77, 3, 224, 224)
256
+ feats = []
257
+ for i in range(0, NUM_FRAMES, batch_frames):
258
+ with torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=use_amp):
259
+ feats.append(enc._backbone_cls(x[i:i + batch_frames]).float())
260
+ out[r] = torch.cat(feats).cpu().numpy().astype(np.float16)
261
+ if progress and (r + 1) % 10 == 0:
262
+ progress(f'Đang chạy DINOv3: {r + 1}/{len(rows)} đoạn')
263
+ return out