File size: 38,760 Bytes
039299d
3e4f4a6
 
039299d
3e4f4a6
039299d
 
4be45cc
039299d
0b509ad
90970fd
9bd7dc4
9f66df3
 
 
4be45cc
0a7174f
2fbdb13
 
 
 
4be45cc
 
 
 
 
 
 
 
 
e020aa8
3e4f4a6
 
 
 
 
 
 
039299d
 
 
 
 
 
 
3e4f4a6
16a2821
3e4f4a6
039299d
7c704b6
039299d
3e4f4a6
d8be51e
3e4f4a6
 
 
 
 
 
 
 
 
0b509ad
 
3e4f4a6
 
0b509ad
 
0a7174f
 
 
 
 
 
 
 
0b509ad
3e4f4a6
 
039299d
 
3e4f4a6
039299d
3e4f4a6
 
039299d
3e4f4a6
039299d
 
3e4f4a6
4be45cc
 
0a7174f
4be45cc
 
 
 
b070005
 
 
 
 
 
 
 
 
 
 
 
 
4be45cc
3872cb9
 
 
 
 
 
 
 
 
 
 
 
3e4f4a6
 
 
 
039299d
 
 
4be45cc
039299d
3e4f4a6
4be45cc
039299d
4be45cc
 
3e4f4a6
4be45cc
0a7174f
 
039299d
 
 
3e4f4a6
039299d
 
71289d6
039299d
 
 
 
3e4f4a6
 
039299d
3e4f4a6
039299d
 
e020aa8
039299d
3e4f4a6
 
039299d
4be45cc
 
 
039299d
 
71289d6
9f66df3
a178790
 
c1c083d
a178790
c1c083d
 
 
a178790
c1c083d
 
 
 
9bd7dc4
c1c083d
 
 
 
 
 
 
 
a178790
 
c1c083d
a178790
 
 
 
c1c083d
 
 
 
 
 
a178790
c1c083d
9bd7dc4
c1c083d
 
a178790
c1c083d
 
 
a178790
 
 
4be45cc
 
 
 
 
 
cd5ac69
 
97c8ca6
 
665ae94
4be45cc
 
 
 
97c8ca6
 
 
 
4be45cc
 
 
 
97c8ca6
 
4be45cc
97c8ca6
4be45cc
 
97c8ca6
4be45cc
97c8ca6
4be45cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7100558
4be45cc
 
 
 
 
 
 
 
 
7100558
4be45cc
 
 
 
 
 
 
 
 
 
 
adf277b
 
 
 
 
 
 
4be45cc
 
 
 
adf277b
4be45cc
ac3ca2a
 
adf277b
ac3ca2a
 
adf277b
ac3ca2a
 
 
0a7174f
adf277b
4be45cc
ac3ca2a
adf277b
4be45cc
 
ac3ca2a
4be45cc
adf277b
4be45cc
 
 
 
ac3ca2a
adf277b
4be45cc
 
 
 
 
 
 
 
 
 
 
 
 
 
adf277b
4be45cc
 
adf277b
 
4be45cc
 
 
039299d
0c40cb3
b7d74eb
774d4f3
 
b7d74eb
039299d
 
3e4f4a6
0a7174f
 
774d4f3
 
 
 
b7d74eb
 
3e4f4a6
039299d
 
774d4f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e2340f
774d4f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e2340f
 
 
 
 
774d4f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7d74eb
774d4f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
039299d
 
774d4f3
 
 
 
 
 
 
 
 
 
 
039299d
0fad093
3e4f4a6
774d4f3
b7d74eb
774d4f3
3e4f4a6
 
b7d74eb
 
774d4f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a178790
4be45cc
 
 
 
 
 
 
0c40cb3
 
 
4be45cc
 
 
0c40cb3
4be45cc
 
 
 
 
 
 
 
0a7174f
 
 
 
 
 
 
20ce931
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7174f
039299d
3e4f4a6
039299d
774d4f3
b7d74eb
 
774d4f3
4be45cc
 
 
 
 
 
 
 
 
9f66df3
4be45cc
 
 
 
 
 
9f66df3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11a7573
 
 
 
9f66df3
 
 
 
 
 
 
 
 
 
 
 
 
11a7573
 
 
 
9f66df3
 
 
 
 
 
9bc2d45
 
 
 
9f66df3
9bc2d45
 
 
 
 
 
1708abe
9bc2d45
9f66df3
 
9bc2d45
9f66df3
 
 
9bc2d45
9f66df3
9bc2d45
9f66df3
 
 
 
774d4f3
 
9bc2d45
 
 
0cb9df5
9bc2d45
 
 
 
774d4f3
9bc2d45
0cb9df5
 
 
 
ad79b46
0cb9df5
9bc2d45
0cb9df5
 
 
9bc2d45
0cb9df5
 
 
 
9bc2d45
 
 
 
 
 
 
 
 
 
 
 
 
 
cbea94d
 
9bc2d45
 
 
 
 
 
 
 
 
 
 
 
 
cbea94d
 
 
 
 
 
 
 
 
9bc2d45
 
 
 
 
 
 
 
70ae0eb
 
 
9bc2d45
cbea94d
 
9bc2d45
cbea94d
 
 
 
 
 
80a8480
cbea94d
 
 
 
 
 
 
 
9bc2d45
 
 
 
 
 
 
cbea94d
9bc2d45
 
cbea94d
 
9bc2d45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f66df3
9bc2d45
 
 
 
 
cbea94d
9f66df3
 
 
 
0cb9df5
 
9f66df3
 
b7d74eb
 
ad79b46
b7d74eb
ad79b46
 
b7d74eb
3e4f4a6
 
 
ad79b46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e4f4a6
 
e020aa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fbdb13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e020aa8
3e4f4a6
 
0a7174f
3e4f4a6
 
 
 
 
039299d
7eb06fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7174f
 
3e4f4a6
039299d
 
3e4f4a6
 
20ce931
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
import os
import json
import httpx
import torch
from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from typing import List, Optional, Dict 
from collections import Counter
from fastapi.staticfiles import StaticFiles
from huggingface_hub import HfApi,hf_hub_download
import datetime
import csv, sys
import io
import numpy as np
from datasets import load_dataset 
import time  # ✨ 新增:用來量測 performance
import psutil
import shutil
import platform


# ⚠️ 注意: som_analyzer.py 必須存在於同一目錄
try:
    from som_analyzer import SOMAnalyzer 
    SOM_FILE_AVAILABLE = True
except ImportError:
    print("⚠️  WARNING: 'som_analyzer.py' not found. SOM features will be disabled.")
    SOM_FILE_AVAILABLE = False
    
CURRENT_TAG = os.getenv("MODEL_TAG", "main")
# ====== FastAPI 初始化 ======
app = FastAPI(
    title="Malvec Prediction Space (A)",
    description="Handles inference and optionally triggers LoRA fine-tuning (Space B).",
    version="1.3"
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# ====== 模型設定 ======
MODEL_REPO = os.getenv("MODEL_REPO", "malvec/Malvec_predict")
HF_TOKEN = os.getenv("HF_TOKEN")
DEVICE = torch.device("cpu")
HF_DATASET_REPO = "lyi029/malvec-embeddings-new"

# ====== 連接 Space B ======
SPACE_B_URL = os.getenv("SPACE_B_URL", "https://malvec-model-update-test.hf.space")

# ====== Cache & 目錄 ======
CACHE_DIR = "/tmp/hf_cache"
os.environ.update({
    "HF_HOME": CACHE_DIR,
    "TRANSFORMERS_CACHE": CACHE_DIR,
    "HUGGINGFACE_HUB_CACHE": CACHE_DIR
})
os.makedirs(CACHE_DIR, exist_ok=True)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
RESULT_DIR = os.path.join(BASE_DIR, "results")
os.makedirs("results", exist_ok=True)

app.mount("/results", StaticFiles(directory=RESULT_DIR), name="results")

# ====== 簡單 Performance 統計 ======
PERF_STATS = {
    "predict_calls": 0,
    "predict_total_seconds": 0.0,
    "predict_last_ms": 0.0,
    "predict_last_files": 0,
    "last_updated": None,
}

# ====== 載入模型 ======
print("🤗 Loading model from:", MODEL_REPO)
tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, token=HF_TOKEN)
model = AutoModelForSequenceClassification.from_pretrained(
    MODEL_REPO,
    token=HF_TOKEN,
    output_attentions=True,
    output_hidden_states=True
)
model.to(DEVICE).eval()
print("✅ Model loaded successfully")


# ===== 新增:載入 SOM 模型 (from app.py) =====
print("🧠 Initializing SOM Analyzer...")
SOM_REPO = os.getenv("SOM_REPO", "malvec/codebert_Malvec")  # ✨ 補上 SOM_REPO,避免 NameError
SOM_AVAILABLE = False

if SOM_FILE_AVAILABLE: # 檢查 'som_analyzer.py' 是否 import 成功
    try:
        # ✅ 直接使用 repo 內的本地檔案
        #    (假設 app.py 和 .npy/.pkl 檔案在同一層級)
        print("   Loading SOM files from local repository...")
        som_weights_path = "som_weights.npy"
        background_data_path = "som_background_data.pkl"

        # 檢查檔案是否存在
        if not os.path.exists(som_weights_path):
            raise FileNotFoundError(f"{som_weights_path} not found in this repo.")
        if not os.path.exists(background_data_path):
            raise FileNotFoundError(f"{background_data_path} not found in this repo.")

        print("   Local files found.")

        som_analyzer = SOMAnalyzer(
            som_weights_path=som_weights_path,
            background_data_path=background_data_path
        )
        print("✅ SOM Analyzer initialized successfully!")
        SOM_AVAILABLE = True
    except Exception as e:
        print(f"⚠️  SOM Analyzer initialization failed: {e}")
        print("   SOM analysis will be disabled")
else:
     print("   SOM analysis disabled because 'som_analyzer.py' is missing.")

# ----------------------------------------------------------
#                   ROUTES
# ----------------------------------------------------------

@app.get("/")
def home():
    return {
        "message": "Malware Classifier API (Space A) with SOM", # ✨
        "model": MODEL_REPO,
        "space_b_url": SPACE_B_URL,
        "som_status": "Available" if SOM_AVAILABLE else "Disabled", # ✨
        "endpoints": {
            "/predict": "POST - Upload TXT files for prediction (with SOM)",
            "/predict-batch": "POST - Simplified batch prediction (from app.py)",
            "/model-info": "GET - Get model information",
            "/attention-heatmap": "POST - Generate attention heatmap (with CLIP)",
            "/check-new-samples": "POST - Trigger Space B Active Learning",
            "/performance": "GET - Simple runtime performance stats"  # ✨ 新增說明
        }
    }


@app.get("/model-info")
def get_model_info():
    """取得模型資訊"""
    id2label_sample = {}
    if hasattr(model.config, 'id2label'):
        sample_keys = list(model.config.id2label.keys())[:3]
        id2label_sample = {
            k: {"type": str(type(k).__name__), "value": model.config.id2label[k]}
            for k in sample_keys
        }

    return {
        "model_name": MODEL_REPO,
        "current_tag": CURRENT_TAG,   # 👈 回報目前版本
        "num_labels": model.config.num_labels,
        "labels": list(model.config.id2label.values())
        if hasattr(model.config, 'id2label') else None,
        "device": str(DEVICE),
        "id2label_sample": id2label_sample,
        "som_model_repo": SOM_REPO, # ✨
        "som_available": SOM_AVAILABLE # ✨
    }


HF_DATASET_REPO = "lyi029/malvec-embeddings-new"

def upload_embeddings_to_hub(local_path: str):
    """自動建立 Dataset 並分批上傳 embeddings_log.jsonl"""
    api = HfApi()
    timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    remote_path = f"logs/embeddings_{timestamp}.jsonl"

    try:
        # 確認 Dataset 存在
        try:
            api.dataset_info(repo_id=HF_DATASET_REPO, token=HF_TOKEN)
            print(f"📂 Dataset {HF_DATASET_REPO} 已存在。")
        except Exception as e:
            if e.response is not None and e.response.status_code == 404:
                print(f"🆕 Dataset 不存在,建立中...")
                api.create_repo(repo_id=HF_DATASET_REPO, repo_type="dataset", token=HF_TOKEN)
                print(f"✅ 已建立 Dataset: {HF_DATASET_REPO}")
            else:
                raise

        print(f"🚀 上傳 {local_path} → {HF_DATASET_REPO}/{remote_path}")
        api.upload_file(
            path_or_fileobj=local_path,
            path_in_repo=remote_path,
            repo_id=HF_DATASET_REPO,
            repo_type="dataset",
            token=HF_TOKEN,
        )
        print(f"☁️ 已上傳 embeddings 至 {HF_DATASET_REPO}/{remote_path}")

        # 上傳後清空本地檔案(避免爆 container)
        open(local_path, "w").close()
        print(f"🧹 已清空本地 {local_path}")

        return True

    except Exception as e:
        print(f"❌ HF API HTTP error: {e.response.status_code} - {e.response.text}")
        return False
    except Exception as e:
        import traceback
        print("❌ Upload failed:", e)
        traceback.print_exc()
        return False


# ----------------------------------------------------------
#         新增:SOM 輔助函數 (from app.py)
# ----------------------------------------------------------

async def get_embeddings_from_hf_dataset(filename: str) -> Optional[List[np.ndarray]]:
    """ (from app.py) """
    try:
        base_name = filename.rsplit('.', 1)[0].lower()
        print(f"\n📦 Fetching embeddings from HF dataset for base name: {base_name}")
        
        dataset = load_dataset("lyi029/malvec-embeddings-new", split="train", streaming=True)
        embeddings = []
        count = 0
        for sample in dataset:
            sample_filename = sample.get('source', '') or sample.get('filename', '')
            
            # ✅ 2. 檢查 dataset source (例如 "unpacked_myfile_67.txt")
            #    是否 *包含* 這個基礎檔名 (例如 "myfile_67")
            if base_name in sample_filename.lower():
                emb = sample.get('embedding') or sample.get('emb')
                if emb is not None:
                    embeddings.append(np.array(emb, dtype=np.float32))
                    count += 1
            if count >= 1000: break # 保留限制
        
        if embeddings:
            print(f"✅ Found {len(embeddings)} embeddings for base name {base_name}")
            return embeddings
        else:
            print(f"⚠️  No embeddings found for base name {base_name} in dataset")
            return None
            
    except Exception as e:
        print(f"❌ Error fetching from HF dataset: {e}")
        return None

def analyze_som_region_probability(
    som_analyzer: SOMAnalyzer,
    center_row: int,
    center_col: int,
    embeddings: List[np.ndarray],
    radius: int = 2
) -> Dict[str, float]:
    """ (from app.py) """
    print(f"   🔍 Analyzing region around ({center_row}, {center_col}) with radius={radius}")
    region_samples = []
    for emb in embeddings:
        sample_row, sample_col = som_analyzer.som.winner(emb) # 
        if abs(sample_row - center_row) <= radius and abs(sample_col - center_col) <= radius:
            region_samples.append(emb)
    print(f"      Found {len(region_samples)} samples in region")
    if len(region_samples) == 0:
        return {"dropper": 0.0, "APT30": 0.0}
    
    feature_counts = {"dropper": [], "spreader": [], "APT30": [], "Codoso_Gh0st_1": []}
    
    if hasattr(som_analyzer, 'background_embeddings') and hasattr(som_analyzer, 'background_labels'):
        for i, bg_emb in enumerate(som_analyzer.background_embeddings):
            bg_row, bg_col = som_analyzer.som.winner(bg_emb) # 
            if abs(bg_row - center_row) <= radius and abs(bg_col - center_col) <= radius:
                for feature_name in feature_counts.keys():
                    if feature_name in som_analyzer.background_labels:
                        feature_counts[feature_name].append(
                            som_analyzer.background_labels[feature_name][i]
                        )
                        
    probabilities = {}
    for feature_name, values in feature_counts.items():
        if len(values) > 0:
            prob = sum(values) / len(values)
            probabilities[feature_name] = float(prob)
        else:
            probabilities[feature_name] = 0.0
    return probabilities


async def analyze_with_som(embedding, predicted_family, filename):
    """
    (from app.py)
    ✨ 修改後的 SOM 分析邏輯:
    1. 優先從 HF Dataset 抓取 embeddings。
    2. 如果找到,用它們的「平均值」來決定座標。
    3. 如果沒找到,才用模型即時產生的 embedding。
    """
    if not SOM_AVAILABLE:
        print("⚠️  SOM analysis disabled")
        return None
    try:
        print("\n🗺️  Performing SOM analysis (New Logic)...")
        
        if isinstance(embedding, list):
            embedding_to_use = np.array(embedding, dtype=np.float32)
        else:
            embedding_to_use = embedding
        
        winner_row, winner_col = som_analyzer.find_winner_neuron(embedding_to_use)
        print(f"   📍 Winner neuron: ({winner_row}, {winner_col}) (Source: high-attention segment)")
        
        hf_embeddings = await get_embeddings_from_hf_dataset(filename)
        data_source = "high-attention (pos) + " 

        if hf_embeddings and len(hf_embeddings) > 0:
            print(f"   Analysing region using {len(hf_embeddings)} HF embeddings...")
            features_prob = analyze_som_region_probability(
                som_analyzer, winner_row, winner_col, hf_embeddings, radius=2
            )
            data_source += "hf_dataset (prob)"
        else:
            print(f"⚠️  No HF data for prob, using background data")
            features_dict = som_analyzer.predict_features_from_position(
                winner_row, winner_col, radius=1
            )
            features_prob = {k: float(v) for k, v in features_dict.items()}
            data_source += "background_data (prob)"

        features_binary = {
            feature: 1 if prob > 0.2 else 0 
            for feature, prob in features_prob.items()
        }
        print(f"   ✅ Features detected: {features_binary}")
        
        result = {
            "winner_position": {"row": int(winner_row), "col": int(winner_col)}, 
            "features": features_binary,
            "features_probability": features_prob,
            "data_source": data_source
        }
        print(f"✅ SOM analysis complete!")
        return result
        
    except Exception as e:
        print(f"❌ SOM analysis error: {e}")
        import traceback
        traceback.print_exc()
        return None


@app.post("/predict")
async def predict_malware(files: List[UploadFile] = File(...), original_filename: Optional[str] = None):
    """
    批次預測惡意軟體家族(維持原回傳格式)
    並自動寫入 embeddings_log.jsonl、上傳到 Hugging Face Dataset
    """
    if not files:
        raise HTTPException(status_code=400, detail="No files provided")

    start_time = time.time()  # ✨ 開始量測時間

    print(f"\n{'='*60}")
    print(f"📥 Received {len(files)} files")
    print(f"{'='*60}")

    predictions = []
    all_embeddings = []

    try:
        with torch.no_grad():
            for idx, file in enumerate(files, 1):
                try:
                    content = await file.read()
                    asm_code = content.decode('utf-8').strip()
                    if not asm_code:
                        print(f"⚠️ Skip empty file: {file.filename}")
                        continue

                    print(f"📄 [{idx}/{len(files)}] Processing: {file.filename}")

                    # === Tokenize ===
                    inputs = tokenizer(
                        asm_code,
                        return_tensors="pt",
                        max_length=512,
                        truncation=True,
                        padding=True
                    )
                    inputs = {k: v.to(DEVICE) for k, v in inputs.items()}

                    # === Forward ===
                    outputs = model(**inputs)
                    logits = outputs.logits

                    # === Softmax 機率 ===
                    probs = torch.nn.functional.softmax(logits, dim=-1)
                    prob_list = probs.squeeze().cpu().tolist()

                    # === 取得預測結果 ===
                    confidence, predicted_class = torch.max(probs, dim=-1)
                    predicted_id = predicted_class.item()
                    label_name = (
                        model.config.id2label[predicted_id]
                        if hasattr(model.config, "id2label") and predicted_id in model.config.id2label
                        else f"class_{predicted_id}"
                    )
                    print(f"   🔍 Predicted ID: {predicted_id}, Label: {label_name}")

                    # === Embedding ===
                    if hasattr(outputs, "hidden_states") and outputs.hidden_states is not None:
                        last_hidden = outputs.hidden_states[-1]
                        cls_embedding = last_hidden[:, 0, :].cpu().numpy()[0]
                    else:
                        cls_embedding = logits.cpu().numpy()[0]

                    # === Attention ===
                    max_attention_score = 0.0
                    if hasattr(outputs, "attentions") and outputs.attentions is not None:
                        last_attention = outputs.attentions[-1]
                        avg_attention = last_attention.mean(dim=1)
                        cls_attention = avg_attention[0, 0, :].cpu().numpy()
                        max_attention_score = float(cls_attention.max())

                    # === Collect Results ===
                    predictions.append({
                        "filename": file.filename,
                        "predicted_label": label_name,
                        "confidence": float(confidence.item()),
                        "attention_score": max_attention_score
                    })

                    all_embeddings.append({
                        "source": file.filename,
                        "label": label_name,
                        "embedding": cls_embedding.tolist(),
                        "attention_score": max_attention_score,
                        "text_excerpt": asm_code,
                        "probs": prob_list   # ✅ 新增:完整 softmax 機率
                    })

                    print(f"   ✅ Predicted: {label_name} (confidence: {confidence.item():.3f})")

                except Exception as e:
                    print(f"   ❌ Error processing {file.filename}: {e}")
                    continue

        if not predictions:
            raise HTTPException(status_code=400, detail="No valid files processed")

        # === 多數投票 ===
        label_votes = [p["predicted_label"] for p in predictions]
        vote_counts = Counter(label_votes)
        final_label, final_count = vote_counts.most_common(1)[0]

        print(f"\n📊 Vote distribution: {dict(vote_counts)}")
        print(f"🏆 Final prediction: {final_label} ({final_count}/{len(predictions)} votes)")

        # === 選最高注意力權重的 embedding ===
        same_label_embeddings = [emb for emb in all_embeddings if emb["label"] == final_label]
        best_embedding = (
            max(same_label_embeddings, key=lambda x: x["attention_score"])
            if same_label_embeddings else
            max(all_embeddings, key=lambda x: x["attention_score"])
        )

        print(f"🎯 Selected embedding from: {best_embedding['source']}")
        print(f"   Attention score: {best_embedding['attention_score']:.4f}")

        # === 回傳結果 ===
        result = {
            "final_label": final_label,
            "vote_count": final_count,
            "total_segments": len(predictions),
            "confidence": sum(p["confidence"] for p in predictions) / len(predictions),
            "vote_distribution": dict(vote_counts),
            "embedding": {
                "values": best_embedding["embedding"],
                "source_file": best_embedding["source"],
                "attention_score": best_embedding["attention_score"],
                "dimension": len(best_embedding["embedding"])
            },
            "segment_predictions": predictions
        }
        os.environ["CURRENT_LABEL"] = final_label

        print(f"\n✅ Prediction complete!\n")        

        # === 寫入本地 embeddings_log.jsonl ===
        log_path = os.path.join("results", "embeddings_log.jsonl")
        with open(log_path, "a") as f:
            for emb in all_embeddings:
                f.write(json.dumps(emb) + "\n")
        print(f"📝 Logged {len(all_embeddings)} embeddings locally.")

        # === 上傳到 Hugging Face Dataset ===
        repo_id = "lyi029/malvec-embeddings-new"   # ✅ 你的新 dataset
        api = HfApi()

        try:
            old_data = []
            try:
                old_path = hf_hub_download(
                    repo_id=repo_id,
                    filename="embeddings_log.jsonl",
                    repo_type="dataset",
                    token=HF_TOKEN
                )
                with open(old_path, "r") as f:
                    old_data = [json.loads(l) for l in f if l.strip()]
            except Exception:
                print("ℹ️ No previous embeddings found in dataset.")

            with open(log_path, "r") as f:
                new_data = [json.loads(l) for l in f if l.strip()]

            # 合併去重
            merged_dict = {(d["source"]): d for d in (old_data + new_data)}
            merged = list(merged_dict.values())

            with open(log_path, "w") as f:
                for item in merged:
                    f.write(json.dumps(item) + "\n")

            api.upload_file(
                path_or_fileobj=log_path,
                path_in_repo="embeddings_log.jsonl",
                repo_id=repo_id,
                repo_type="dataset",
                token=HF_TOKEN,
            )
            print(f"☁️ Uploaded {len(merged)} merged embeddings to dataset: {repo_id}")
        except Exception as e:
            print(f"⚠️ Dataset upload failed: {e}")

        # ===== 新增:執行 SOM 分析 (from app.py) =====
        som_analysis = None
        final_embedding_values = result.get("embedding", {}).get("values")
        
        if SOM_AVAILABLE and final_embedding_values:
            print("\n🗺️  Performing SOM analysis...")
            try:
                filename_for_som = original_filename if original_filename else files[0].filename
                print(f"   Using filename for SOM lookup: {filename_for_som}")
                
                som_analysis = await analyze_with_som(
                    embedding=final_embedding_values,
                    predicted_family=result.get("final_label", "Unknown"),
                    filename=filename_for_som
                )
            except Exception as e:
                print(f"❌ SOM analysis error: {e}")
        
        # 將 SOM 結果附加到最終回傳
        result["som_analysis"] = som_analysis
        print(f"✅ SOM analysis complete.")
        
        # ✨ 更新 performance 統計
        elapsed = time.time() - start_time
        PERF_STATS["predict_calls"] += 1
        PERF_STATS["predict_total_seconds"] += elapsed
        PERF_STATS["predict_last_ms"] = elapsed * 1000.0
        PERF_STATS["predict_last_files"] = len(files)
        PERF_STATS["last_updated"] = datetime.datetime.utcnow().isoformat()
        if len(files) > 0:
            files_per_sec = len(files) / elapsed
        else:
            files_per_sec = 0.0

        print("\n===== 🔬 Inference Performance (this request) =====")
        print(f"  Files processed : {len(files)}")
        print(f"  Elapsed time    : {elapsed:.3f} s")
        print(f"  Avg per file    : {elapsed/len(files):.3f} s/file" if len(files) > 0 else "  Avg per file    : N/A")
        print(f"  Throughput      : {files_per_sec:.2f} files/s")
        print("  Global stats    :")
        print(f"    Total calls   : {PERF_STATS['predict_calls']}")
        print(f"    Total seconds : {PERF_STATS['predict_total_seconds']:.3f} s")
        if PERF_STATS["predict_calls"] > 0:
            avg = PERF_STATS["predict_total_seconds"] / PERF_STATS["predict_calls"]
            print(f"    Avg per call  : {avg:.3f} s/call")
        print("===================================================\n")


        return result

    except Exception as e:
        print(f"\n❌ Error in predict_malware: {e}")
        import traceback
        traceback.print_exc()
        raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}")

# ===== 新增:/predict-batch 路由 (from app.py) =====
@app.post("/predict-batch")
async def predict_batch(files: List[UploadFile] = File(...)):
    """
    (from app.py)
    簡化版: 只返回 label 和 embedding,不包含詳細資訊
    """
    result = await predict_malware(files)
    
    return {
        "final_label": result["final_label"],
        "embedding": result["embedding"]["values"]
        # SOM results are not included here, matching app.py's behavior
    }

csv.field_size_limit(sys.maxsize)

JUMP_MNEMONICS = {"jmp", "je", "jne", "jl", "jg", "jle", "jge", "call", "ret"}

def _split_into_basic_blocks(tokens):
    """把指令 tokens 拆成 basic blocks(遇到跳轉/ret 就斷)"""
    blocks, cur = [], []
    for tok in tokens:
        cur.append(tok)
        if tok.lower() in JUMP_MNEMONICS:
            blocks.append(cur)
            cur = []
    if cur:
        blocks.append(cur)
    return blocks

def _block_attention_score(tokens, chunk_size=512):
    """
    對單一 block 計算注意力:
    - 以 512 token 為單位分塊
    - 取最後一層 attention → head 平均 → 整體平均
    - 多個 chunk 取平均
    """
    scores = []
    for i in range(0, len(tokens), chunk_size):
        chunk = tokens[i:i+chunk_size]
        inputs = tokenizer(
            chunk,
            return_tensors="pt",
            is_split_into_words=True,
            truncation=True,
            max_length=chunk_size,
            padding=False
        )
        inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
        with torch.no_grad():
            out = model(**inputs, output_attentions=True)
        last_attn = out.attentions[-1]            # (1, heads, seq, seq)
        mean_attn = last_attn.mean(dim=1).mean()  # scalar
        scores.append(mean_attn.item())
    return float(np.mean(scores)) if scores else 0.0

@app.post("/attention-heatmap")
async def attention_heatmap(file: UploadFile = File(...)):
    """
    1️⃣ 從 disasm token 生成 block-level attention heatmap
    2️⃣ 將 heatmap 轉成 base64 圖
    3️⃣ 用 CLIP 將 heatmap 轉成 embedding
    4️⃣ 上傳至 dataset 並在同 label 裡找出最相似的 heatmap
    """
    import io, base64, matplotlib.pyplot as plt, numpy as np, datetime, json
    from PIL import Image
    from transformers import CLIPProcessor, CLIPModel
    from sklearn.metrics.pairwise import cosine_similarity
    from huggingface_hub import HfApi, hf_hub_download

    HF_HEATMAP_REPO = "lyi029/malvec-heatmap"
    os.makedirs("results", exist_ok=True)

    try:
        # === Step 1. 讀檔 ===
        content = await file.read()
        text = content.decode("utf-8", errors="ignore")

        # === Step 2. 解析 disasm token ===
        tokens = []
        for line in text.replace("\n", " ").split("</s>"):
            toks = [t.strip() for t in line.split() if t.strip()]
            if toks:
                tokens.extend(toks)

        print(f"📦 Total tokens parsed: {len(tokens)}")

        # === Step 3. 拆 basic blocks ===
        blocks = _split_into_basic_blocks(tokens)[:1000]
        print(f"📊 Total blocks: {len(blocks)}")

        # === Step 4. 計算 block-level attention ===
        scores = [_block_attention_score(blk) for blk in blocks]
        if not scores:
            return {"error": "No valid blocks parsed"}

        # === Step 5. 畫出 heatmap 圖像 ===
        fig, ax = plt.subplots(figsize=(10, 2))
        heatmap_data = np.expand_dims(scores, axis=0)
        im = ax.imshow(heatmap_data, cmap="viridis", aspect="auto")
        plt.colorbar(im, ax=ax, orientation="vertical", label="Attention Score")
        ax.set_title("Attention Heatmap")
        ax.set_xlabel("Block Index")
        ax.set_yticks([])
        plt.tight_layout()

        buf = io.BytesIO()
        plt.savefig(buf, format="png", dpi=200)
        buf.seek(0)
        img_base64 = base64.b64encode(buf.read()).decode("utf-8")
        plt.close(fig)

        b64_uri = f"data:image/png;base64,{img_base64}"

        # === Step 6. 用 CLIP 轉成 embedding ===
        clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
        clip_proc = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")

        img = Image.open(io.BytesIO(base64.b64decode(img_base64))).convert("RGB")
        inputs = clip_proc(images=img, return_tensors="pt")
        with torch.no_grad():
            emb = clip_model.get_image_features(**inputs)
        emb = emb / emb.norm(p=2, dim=-1, keepdim=True)
        emb_vec = emb.squeeze().cpu().numpy().tolist()

        # === Step 7. 取得當前 label ===
        current_label = os.getenv("CURRENT_LABEL", "unknown").strip()
        print(f"[heatmap] 🏷️ Current label: {current_label}")

        # === Step 8. 讀取舊 heatmap dataset ===
        api = HfApi()
        old_records = []
        try:
            old_path = hf_hub_download(
                repo_id=HF_HEATMAP_REPO,
                filename="heatmaps_log.jsonl",
                repo_type="dataset",
                token=HF_TOKEN
            )
            with open(old_path, "r") as f:
                for line in f:
                    line = line.strip()
                    if not line:
                        continue
                    try:
                        record = json.loads(line)
                        if isinstance(record, dict):
                            old_records.append(record)
                    except json.JSONDecodeError:
                        print(f"[heatmap-load] ⚠️ Skip invalid line.")
        except Exception:
            print("ℹ️ No previous dataset found, will create new.")

        # === Step 9. 找同 label 最相似的 heatmap ===
        most_similar_id, most_similar_score, most_similar_img = None, -1, None
        if old_records:
            same_label = [
                rec for rec in old_records
                if rec.get("label") == current_label 
                and rec.get("embedding")
                and rec.get("source") != file.filename
            ]
            print(f"[heatmap-match] Found {len(same_label)} old heatmaps under label '{current_label}'")

            if same_label:
                X = np.array([rec["embedding"] for rec in same_label if rec.get("embedding")])
                if X.size > 0:
                    sim_scores = cosine_similarity([emb_vec], X)[0]
                    max_idx = int(np.argmax(sim_scores))
                    best_sim = float(sim_scores[max_idx])
                    best_rec = same_label[max_idx]
                    if best_sim < 2:  # 排除完全相同
                        most_similar_id = best_rec.get("source")
                        most_similar_score = best_sim
                        most_similar_img = best_rec.get("image_base64")
                        print(f"[heatmap-match] ✅ Best match: {most_similar_id}, sim={best_sim:.4f}")
                    else:
                        print(f"[heatmap-match] ⚠️ No sufficiently different heatmaps found under label '{current_label}'")
        else:
            print(f"[heatmap-match] ⚠️ No existing heatmaps for label '{current_label}' yet")

        # === Step 10. 儲存新紀錄並上傳 ===
        new_record = {
            "timestamp": datetime.datetime.now().isoformat(),
            "label": current_label,
            "embedding": emb_vec,
            "source": file.filename,
            "image_base64": b64_uri,
        }

        merged_dict = {rec["source"]: rec for rec in (old_records + [new_record])}
        merged_list = list(merged_dict.values())

        local_path = os.path.join("results", "heatmaps_log.jsonl")
        with open(local_path, "w") as f:
            for rec in merged_list:
                f.write(json.dumps(rec) + "\n")

        try:
            api.upload_file(
                path_or_fileobj=local_path,
                path_in_repo="heatmaps_log.jsonl",
                repo_id=HF_HEATMAP_REPO,
                repo_type="dataset",
                token=HF_TOKEN,
            )
            print(f"☁️ Uploaded {len(merged_list)} heatmaps to dataset: {HF_HEATMAP_REPO}")
        except Exception as e:
            print(f"⚠️ Upload failed: {e}")

        # === Step 11. 回傳結果 ===
        return {
            "label": current_label,
            "attention_heatmap": b64_uri,
            "embedding_dim": len(emb_vec),
            "most_similar_in_label": most_similar_id,
            "similarity_score": most_similar_score,
            "similar_heatmap_image": most_similar_img,
        }

    except Exception as e:
        print(f"❌ attention_heatmap error: {e}")
        import traceback
        traceback.print_exc()
        return {"error": str(e)}


@app.post("/check-new-samples")
async def check_new_samples():
    """
    觸發 Space B 的 Active Learning 探測與 LoRA 訓練流程
    並將 Space B 的回傳結果原樣傳回前端
    """
    if not SPACE_B_URL:
        raise HTTPException(status_code=400, detail="SPACE_B_URL not set")

    try:
        async with httpx.AsyncClient(timeout=600.0) as client:
            params = {"batch_size": 1000, "mmd_threshold": 0.2, "entropy_threshold": 1.1}
            resp = await client.post(f"{SPACE_B_URL}/check-new-samples", params=params)
            print(f"🚀 Space B /check-new-samples → HTTP {resp.status_code}")

            # 嘗試解析回傳 JSON
            try:
                data = resp.json()
                print(f"📦 Space B response: {data}")
                return data  # ✅ 原樣回傳給前端
            except Exception as e:
                print(f"⚠️ Failed to parse Space B JSON: {e}")
                return {
                    "status": "error",
                    "message": "Invalid JSON from Space B",
                    "raw_text": resp.text[:500]
                }

    except Exception as e:
        print("❌ Failed to contact Space B:", e)
        raise HTTPException(status_code=500, detail=f"Failed to contact Space B: {str(e)}")


def _reload_model_by_tag(tag: str):
    global tokenizer, model, CURRENT_TAG
    print(f"♻️ Reloading model: {MODEL_REPO}@{tag}")
    tok = AutoTokenizer.from_pretrained(MODEL_REPO, token=HF_TOKEN, revision=tag)
    mdl = AutoModelForSequenceClassification.from_pretrained(
        MODEL_REPO, token=HF_TOKEN, revision=tag,
        output_attentions=True, output_hidden_states=True
    )
    mdl.to(DEVICE).eval()
    tokenizer = tok
    model = mdl
    CURRENT_TAG = tag
    print("✅ Reloaded.")


@app.post("/api/update-model")
async def update_model(payload: dict):
    tag = payload.get("tag")
    if not tag:
        raise HTTPException(400, "missing 'tag'")
    try:
        _reload_model_by_tag(tag)
        return {"status":"ok", "tag": tag}
    except Exception as e:
        raise HTTPException(500, f"reload failed: {e}")
    
@app.get("/performance")
async def performance():
    """
    回傳推論 performance + 系統資源使用狀況
    """
    # === 計算平均推論時間 ===
    avg_sec = (
        PERF_STATS["predict_total_seconds"] / PERF_STATS["predict_calls"]
        if PERF_STATS["predict_calls"] > 0 else 0.0
    )

    # === 系統資訊 ===
    cpu_percent = psutil.cpu_percent(interval=0.2)
    cpu_cores = psutil.cpu_count(logical=True)
    cpu_model = platform.processor() or "Unknown CPU"

    # === 記憶體資訊 ===
    mem = psutil.virtual_memory()
    memory_info = {
        "total_gb": round(mem.total / 1024**3, 2),
        "used_gb": round(mem.used / 1024**3, 2),
        "free_gb": round(mem.available / 1024**3, 2),
        "percent": mem.percent
    }

    # === Python Process 記憶體使用 ===
    proc = psutil.Process(os.getpid())
    proc_mem = proc.memory_info()
    process_memory = {
        "rss_mb": round(proc_mem.rss / 1024**2, 2),
        "vms_mb": round(proc_mem.vms / 1024**2, 2),
    }

    # === 磁碟空間 ===
    disk = shutil.disk_usage("/")
    disk_info = {
        "total_gb": round(disk.total / 1024**3, 2),
        "used_gb": round(disk.used / 1024**3, 2),
        "free_gb": round(disk.free / 1024**3, 2),
    }

    base_info = {
        "model_name": MODEL_REPO,
        "current_tag": CURRENT_TAG,
        "device": str(DEVICE),
        "som_available": SOM_AVAILABLE,
        "space_b_url": SPACE_B_URL,
    }

    perf_info = {
        "predict_calls": PERF_STATS["predict_calls"],
        "predict_total_seconds": PERF_STATS["predict_total_seconds"],
        "predict_avg_seconds": avg_sec,
        "predict_last_ms": PERF_STATS["predict_last_ms"],
        "predict_last_files": PERF_STATS["predict_last_files"],
        "last_updated": PERF_STATS["last_updated"],
    }

    resource_info = {
        "cpu": {
            "model": cpu_model,
            "cores": cpu_cores,
            "usage_percent": cpu_percent,
        },
        "memory": memory_info,
        "process_memory": process_memory,
        "disk": disk_info,
    }

    # 嘗試從 Space B 取得 performance
    space_b_perf = None
    if SPACE_B_URL:
        try:
            async with httpx.AsyncClient(timeout=5.0) as client:
                r = await client.get(f"{SPACE_B_URL}/performance")
                if r.status_code == 200:
                    space_b_perf = r.json()
        except Exception:
            space_b_perf = None

    return {
        "base": base_info,
        "space_a_performance": perf_info,
        "system_resources": resource_info,
        "space_b_performance": space_b_perf,
    }



# ----------------------------------------------------------
#                 健康檢查 & Performance
# ----------------------------------------------------------
@app.get("/health")
def health():
    return {"status": "ok", "space_b_url": SPACE_B_URL, "model": MODEL_REPO}


# @app.get("/performance")
# async def performance():
#     """
#     簡單回報目前的推論 performance 統計
#     (目前只統計 /predict 的執行時間與呼叫次數)
#     """
#     avg_sec = (
#         PERF_STATS["predict_total_seconds"] / PERF_STATS["predict_calls"]
#         if PERF_STATS["predict_calls"] > 0 else 0.0
#     )

#     base_info = {
#         "model_name": MODEL_REPO,
#         "current_tag": CURRENT_TAG,
#         "device": str(DEVICE),
#         "som_available": SOM_AVAILABLE,
#         "space_b_url": SPACE_B_URL,
#     }

#     perf_info = {
#         "predict_calls": PERF_STATS["predict_calls"],
#         "predict_total_seconds": PERF_STATS["predict_total_seconds"],
#         "predict_avg_seconds": avg_sec,
#         "predict_last_ms": PERF_STATS["predict_last_ms"],
#         "predict_last_files": PERF_STATS["predict_last_files"],
#         "last_updated": PERF_STATS["last_updated"],
#     }

#     # (可選)試著從 Space B 拿 performance(如果那邊有 /performance 的話)
#     space_b_perf = None
#     if SPACE_B_URL:
#         try:
#             async with httpx.AsyncClient(timeout=5.0) as client:
#                 r = await client.get(f"{SPACE_B_URL}/performance")
#                 if r.status_code == 200:
#                     space_b_perf = r.json()
#         except Exception:
#             space_b_perf = None

#     return {
#         "base": base_info,
#         "space_a_performance": perf_info,
#         "space_b_performance": space_b_perf,
#     }


# ===== Hugging Face Space 啟動 =====
if __name__ == "__main__":
    import uvicorn
    port = int(os.getenv("PORT", 7860))
    uvicorn.run(app, host="0.0.0.0", port=port)