HARSHIT-hash-07 commited on
Commit
f5cd164
·
1 Parent(s): c398671

feat: implement HQ AI Bridge mode with high-fidelity motion restoration and HF Hub integration

Browse files
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ weights_hq/
2
+ *.ckpt
3
+ *.pt
backend/debug_large.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import numpy as np
4
+ import torch
5
+
6
+ # Setup paths
7
+ CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
8
+ if CURRENT_DIR not in sys.path:
9
+ sys.path.append(CURRENT_DIR)
10
+
11
+ from sign_bridge_inference import SignBridgeInference
12
+
13
+ # POINT TO THE LARGE CHECKPOINT
14
+ LARGE_MODEL_PATH = "/Users/harshit/Documents/WEBSITE_EXPLO/sign_idd_model_20260121_171210/best.ckpt"
15
+ MODEL_ROOT = os.path.dirname(LARGE_MODEL_PATH)
16
+
17
+ print(f"Loading LARGE model from: {LARGE_MODEL_PATH}")
18
+ # SignBridgeInference expects a weights directory with 'best.ckpt'
19
+ engine = SignBridgeInference(MODEL_ROOT)
20
+
21
+ text = "Today weather rain"
22
+ print(f"Translating: {text}")
23
+ skeletons = engine.translate(text, sampling_steps=50)
24
+
25
+ skel_array = np.array(skeletons)
26
+ skel_std = np.std(skel_array, axis=0).mean()
27
+ skel_mean = np.mean(skel_array)
28
+ skel_min = np.min(skel_array)
29
+ skel_max = np.max(skel_array)
30
+
31
+ print("-" * 30)
32
+ print(f"Frames: {len(skeletons)}")
33
+ print(f"Mean Coordinate Value: {skel_mean:.6f}")
34
+ print(f"Min Coord: {skel_min:.6f}, Max Coord: {skel_max:.6f}")
35
+ print(f"Average Variance (STD) across frames: {skel_std:.6f}")
36
+
37
+ if skel_std < 1e-4:
38
+ print("CRITICAL: The LARGE model is also still?!")
39
+ else:
40
+ print("SUCCESS: Motion detected in LARGE model!")
41
+
42
+ from video_renderer import render_skeleton_to_video
43
+ output_path = os.path.join(CURRENT_DIR, "debug_large_model.mp4")
44
+ render_skeleton_to_video(skeletons, output_path)
45
+ print(f"Video rendered to: {output_path}")
backend/debug_large_model.mp4 ADDED
Binary file (23.3 kB). View file
 
backend/main.py CHANGED
@@ -8,8 +8,10 @@ if BACKEND_DIR not in sys.path:
8
 
9
  try:
10
  from .model_loader import SignModel
 
11
  except (ImportError, ValueError):
12
  from model_loader import SignModel
 
13
 
14
  from fastapi import FastAPI, HTTPException
15
  from fastapi.middleware.cors import CORSMiddleware
@@ -66,3 +68,14 @@ async def translate_text(request: TranslationRequest):
66
  }
67
  except Exception as e:
68
  raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  try:
10
  from .model_loader import SignModel
11
+ from .model_loader_hq import sign_model_hq
12
  except (ImportError, ValueError):
13
  from model_loader import SignModel
14
+ from model_loader_hq import sign_model_hq
15
 
16
  from fastapi import FastAPI, HTTPException
17
  from fastapi.middleware.cors import CORSMiddleware
 
68
  }
69
  except Exception as e:
70
  raise HTTPException(status_code=500, detail=str(e))
71
+ @app.post("/translate_hq", response_model=TranslationResponse)
72
+ async def translate_text_hq(request: TranslationRequest):
73
+ try:
74
+ result = sign_model_hq.inference(request.text)
75
+ return {
76
+ "skeletons": result.get("skeletons", []),
77
+ "video_url": result.get("video_url"),
78
+ "text_processed": request.text
79
+ }
80
+ except Exception as e:
81
+ raise HTTPException(status_code=500, detail=str(e))
backend/model_loader_hq.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import threading
4
+ from typing import Dict, Any, List
5
+
6
+ # Add backend directory to path
7
+ CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
8
+ if CURRENT_DIR not in sys.path:
9
+ sys.path.append(CURRENT_DIR)
10
+
11
+ try:
12
+ from .sign_bridge_inference_hq import SignBridgeInferenceHQ
13
+ except (ImportError, ValueError):
14
+ from sign_bridge_inference_hq import SignBridgeInferenceHQ
15
+
16
+ # HQ Weights are stored in a dedicated directory
17
+ MODEL_ROOT_HQ = os.path.join(os.path.dirname(CURRENT_DIR), "weights_hq")
18
+ CONFIG_PATH_HQ = os.path.join(os.path.dirname(CURRENT_DIR), "model_configs", "Sign-IDD-HQ.yaml")
19
+
20
+ class SignModelHQ:
21
+ """
22
+ Singleton wrapper for the High Fidelity SignBridgeInference engine.
23
+ Uses the uncompressed 1.1GB weights and optimized motion sampling.
24
+ """
25
+ _instance = None
26
+ _lock = threading.Lock()
27
+
28
+ def __new__(cls):
29
+ with cls._lock:
30
+ if cls._instance is None:
31
+ cls._instance = super(SignModelHQ, cls).__new__(cls)
32
+ cls._instance._initialized = False
33
+ return cls._instance
34
+
35
+ def __init__(self):
36
+ if self._initialized:
37
+ return
38
+
39
+ print("Initializing SignBridge HQ Model (High Fidelity Path)...")
40
+ self.engine = None
41
+ self.is_loaded = False
42
+ self._load_error = None
43
+ self._initialized = True
44
+
45
+ # Load in background
46
+ threading.Thread(target=self._load_model_async, daemon=True).start()
47
+
48
+ def _load_model_async(self):
49
+ try:
50
+ # 1. Ensure weight directory exists
51
+ os.makedirs(MODEL_ROOT_HQ, exist_ok=True)
52
+ weight_path = os.path.join(MODEL_ROOT_HQ, "best.ckpt")
53
+
54
+ # 2. Check if weights need to be downloaded (Runtime bypass for 1GB repo limit)
55
+ if not os.path.exists(weight_path):
56
+ print(f"HQ Weights not found at {weight_path}. Attempting download from Hub...")
57
+ from huggingface_hub import hf_hub_download
58
+
59
+ repo_id = os.environ.get("HF_REPO_ID_HQ", "Harshit2907/SignBridge-Weights")
60
+ token = os.environ.get("HF_TOKEN") # Optional: needed if repo is private
61
+
62
+ print(f"Downloading HQ Weights from {repo_id}...")
63
+ downloaded_file = hf_hub_download(
64
+ repo_id=repo_id,
65
+ filename="best.ckpt",
66
+ local_dir=MODEL_ROOT_HQ,
67
+ token=token
68
+ )
69
+ print(f"✅ Download complete: {downloaded_file}")
70
+
71
+ # 3. Initialize the HQ-specific inference engine
72
+ self.engine = SignBridgeInferenceHQ(MODEL_ROOT_HQ)
73
+ self.is_loaded = True
74
+ print("✅ SignBridge HQ Model loaded and ready for high-fidelity inference.")
75
+ except Exception as e:
76
+ self._load_error = str(e)
77
+ print(f"❌ Failed to load SignBridge HQ Model: {e}")
78
+ import traceback
79
+ traceback.print_exc()
80
+
81
+ def inference(self, text: str) -> Dict[str, Any]:
82
+ if not self.is_loaded:
83
+ if self._load_error:
84
+ raise RuntimeError(f"HQ Model failed to load: {self._load_error}")
85
+ raise RuntimeError("HQ Model is still loading. Please try again in 30 seconds.")
86
+
87
+ print(f"HQ Inference Request: '{text}'")
88
+
89
+ try:
90
+ # HIGH FIDELITY PARAMS:
91
+ # We use 90 steps (matching original training) and potentially different guidance or length heuristics
92
+ skeletons = self.engine.translate(text, sampling_steps=90)
93
+
94
+ import uuid
95
+ from video_renderer import render_skeleton_to_video
96
+
97
+ filename = f"hq_gen_{uuid.uuid4().hex[:8]}.mp4"
98
+ output_dir = os.path.join(CURRENT_DIR, "output")
99
+ os.makedirs(output_dir, exist_ok=True)
100
+ output_path = os.path.join(output_dir, filename)
101
+
102
+ # Use standard renderer (stable)
103
+ render_skeleton_to_video(skeletons, output_path)
104
+
105
+ # URL resolution (assumes same static mount)
106
+ video_url = f"https://harshit2907-sign-idd-inference.hf.space/static/{filename}"
107
+ if os.environ.get("LOCAL_DEV"):
108
+ video_url = f"http://127.0.0.1:8001/static/{filename}"
109
+
110
+ return {
111
+ "skeletons": None,
112
+ "video_url": video_url,
113
+ "glosses": self.engine.text_to_glosses(text)
114
+ }
115
+ except Exception as e:
116
+ print(f"HQ Inference error: {e}")
117
+ raise e
118
+
119
+ # Global singleton instance for HQ
120
+ sign_model_hq = SignModelHQ()
backend/sign_bridge_inference_hq.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import torch
4
+ import numpy as np
5
+ from typing import List, Dict
6
+
7
+ # Resolve imports
8
+ CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
9
+ if CURRENT_DIR not in sys.path:
10
+ sys.path.append(CURRENT_DIR)
11
+
12
+ try:
13
+ from .sign_bridge_inference import SignBridgeInference
14
+ except (ImportError, ValueError):
15
+ from sign_bridge_inference import SignBridgeInference
16
+
17
+ class SignBridgeInferenceHQ(SignBridgeInference):
18
+ """
19
+ High Fidelity version of the SignBridge Inference Engine.
20
+ Uses original uncompressed weights and a 'HQ Sampler' tuned for motion.
21
+ """
22
+
23
+ def translate(self, text: str, sampling_steps: int = 90) -> List[List[List[float]]]:
24
+ """
25
+ Translates text to HQ skeletons using the high-fidelity sampler.
26
+ """
27
+ glosses = self.text_to_glosses(text)
28
+ if not glosses:
29
+ return []
30
+
31
+ # Map glosses to indices
32
+ tokens = [self.bos_token] + glosses + [self.eos_token]
33
+ indices = [self.vocab.stoi[t] for t in tokens]
34
+
35
+ dev = self.device
36
+ src_tensor = torch.tensor([indices], dtype=torch.long, device=dev)
37
+ src_mask = (src_tensor != self.vocab.stoi[self.pad_token]).unsqueeze(1).unsqueeze(2)
38
+ src_lengths = torch.tensor([len(indices)], dtype=torch.long, device=dev)
39
+
40
+ # 1. Encode source
41
+ with torch.no_grad():
42
+ encoder_output = self.model.encode(src_tensor, src_lengths, src_mask)
43
+
44
+ # 2. HQ Dynamic Frame Estimation
45
+ # We increase the frames per word to allow for more fluid motion
46
+ # Validation videos usually have approx 100-200 frames for a sentence
47
+ n_frames = max(80, len(glosses) * 20 + 30)
48
+
49
+ trg_mask = torch.ones((1, 1, n_frames), device=dev, dtype=torch.bool)
50
+
51
+ # 3. HQ Sampling with deterministic/stochastic blend
52
+ # Note: We can manually call ddim_sample or use our own loop for better variance control
53
+ # Currently, we'll use the model's ddim_sample but with HQ steps
54
+ print(f"HQ Sampler: Generating {n_frames} frames over {sampling_steps} steps...")
55
+
56
+ with torch.no_grad():
57
+ # Create a mock input_3d just for shape
58
+ mock_input_3d = torch.zeros((1, n_frames, 150), device=dev)
59
+
60
+ # The LARGE model typically performs better at 80-100 steps
61
+ raw_skels = self.model.ACD.ddim_sample(
62
+ encoder_output,
63
+ mock_input_3d,
64
+ src_mask,
65
+ trg_mask,
66
+ sampling_steps=sampling_steps
67
+ )
68
+
69
+ # Use the final prediction (x0)
70
+ raw_skel = raw_skels[-1][0] # (T, 150)
71
+
72
+ # HQ MOTION CALIBRATION:
73
+ # If the model is slightly shy, we can apply a very subtle Dynamic Range expansion
74
+ # skel_std = raw_skel.std()
75
+ # if skel_std < 0.15:
76
+ # raw_skel = (raw_skel - raw_skel.mean()) * 1.2 + raw_skel.mean()
77
+
78
+ return raw_skel.reshape(n_frames, 50, 3).tolist()
79
+
80
+ def text_to_glosses(self, text: str) -> List[str]:
81
+ # Reuse base class preprocessing
82
+ return super().text_to_glosses(text)
model_configs/Sign-IDD-HQ.yaml ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data:
2
+ src: gloss
3
+ trg: skels
4
+ files: files
5
+ train: ./Data/P2014T_Ben/train
6
+ dev: ./Data/P2014T_Ben/dev
7
+ test: ./Data/P2014T_Ben/test
8
+ max_sent_length: 300
9
+ skip_frames: 1
10
+ src_vocab: ./Configs/src_vocab.txt
11
+
12
+ training:
13
+ # ---- keep everything as-is (your PINN config) ----
14
+ overwrite: false
15
+ save_model: true
16
+ random_seed: 27
17
+ optimizer: adam
18
+ learning_rate: 0.001
19
+ learning_rate_min: 0.0002
20
+ weight_decay: 0.0
21
+ clip_grad_norm: 5.0
22
+ batch_size: 64
23
+ scheduling: plateau
24
+ patience: 7
25
+ decrease_factor: 0.7
26
+ early_stopping_metric: dtw
27
+ epochs: 20000
28
+ validation_freq: 2000
29
+ logging_freq: 250
30
+ eval_metric: dtw
31
+
32
+ # ---- checkpoint saving behavior SAME AS the "Base" YAML ----
33
+ # (Base uses: model_dir, overwrite, continue, keep_last_ckpts)
34
+ model_dir: /home/user2/THESIS/Sign-IDD-main/Models/PINN_scratch_run1
35
+ overwrite: false
36
+ continue: true
37
+ keep_last_ckpts: 1
38
+
39
+ # ---- rest of your training config (unchanged) ----
40
+ shuffle: true
41
+ use_cuda: true
42
+ max_output_length: 300
43
+ loss: L1
44
+ bone_loss: MSE
45
+ hand_joint_weight: 1.5
46
+ body_joint_weight: 1.0
47
+ body_bonelen_weight: 0.05
48
+ hand_bonelen_weight: 0.05
49
+ lambda_bone: 0.1
50
+
51
+ # ---------------- PINN (NEW) ----------------
52
+ use_pinn: true
53
+ pinn_weight: 0.1
54
+
55
+ pinn_lambda_bone: 1.0
56
+ pinn_lambda_vel: 0.1
57
+ pinn_lambda_acc: 0.05
58
+ pinn_lambda_fk: 0.5
59
+
60
+ pinn_dt: 1.0
61
+ pinn_rest_from: first_valid
62
+ pinn_detach_rest: true
63
+ pinn_use_huber: true
64
+ pinn_huber_delta: 1.0
65
+
66
+ model:
67
+ encoder:
68
+ type: transformer
69
+ embeddings:
70
+ embedding_dim: 512
71
+ dropout: 0.1
72
+ hidden_size: 512
73
+ ff_size: 2048
74
+ num_layers: 6
75
+ num_heads: 8
76
+ dropout: 0.1
77
+
78
+ trg_size: 150
79
+
80
+ diffusion:
81
+ timesteps: 100
82
+ sampling_timesteps: 90
requirements.txt CHANGED
@@ -7,3 +7,4 @@ pyyaml>=6.0.1
7
  opencv-python-headless>=4.8.1.78
8
  python-dotenv
9
  requests
 
 
7
  opencv-python-headless>=4.8.1.78
8
  python-dotenv
9
  requests
10
+ huggingface-hub