FlameF0X commited on
Commit
f6a9a7e
Β·
verified Β·
1 Parent(s): 31ea115

Create backup/fallback.py

Browse files
Files changed (1) hide show
  1. backup/fallback.py +388 -0
backup/fallback.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from huggingface_hub import list_models, model_info, hf_hub_download, upload_file
3
+ import pandas as pd
4
+ import datetime
5
+ import os
6
+
7
+ # --- DATABASE MANAGER ---
8
+ class ModelDatabase:
9
+ def __init__(self):
10
+ # Initialize an empty DataFrame in memory.
11
+ self.df = pd.DataFrame(columns=["sha256", "repo_id", "filename", "timestamp", "tags"])
12
+ self.dataset_id = "SHA-index/model-dna-index"
13
+ self.token = ""
14
+ self.csv_name = "model_dna.csv"
15
+
16
+ def connect_to_hub(self, dataset_id, token=None):
17
+ """Loads the CSV from a HF Dataset if it exists."""
18
+ self.dataset_id = dataset_id
19
+ self.token = token or os.environ.get("HF_TOKEN")
20
+
21
+ if not self.dataset_id:
22
+ return "⚠️ No Dataset ID provided."
23
+
24
+ try:
25
+ print(f"Attempting to download {self.csv_name} from {self.dataset_id}...")
26
+ path = hf_hub_download(
27
+ repo_id=self.dataset_id,
28
+ filename=self.csv_name,
29
+ repo_type="dataset",
30
+ token=self.token
31
+ )
32
+ self.df = pd.read_csv(path)
33
+ # Ensure columns exist (in case of schema drift)
34
+ for col in ["sha256", "repo_id", "filename", "timestamp", "tags"]:
35
+ if col not in self.df.columns:
36
+ self.df[col] = ""
37
+ return f"βœ… Successfully loaded {len(self.df)} records from {self.dataset_id}."
38
+ except Exception as e:
39
+ # If file doesn't exist, we assume it's a new dataset and will create it on save
40
+ if "404" in str(e) or "EntryNotFound" in str(e):
41
+ return f"⚠️ Connected to {self.dataset_id}, but '{self.csv_name}' was not found. A new file will be created upon saving."
42
+ return f"❌ Error loading from Hub: {e}"
43
+
44
+ def save_to_hub(self):
45
+ """Pushes the current DataFrame to the HF Dataset."""
46
+ if not self.dataset_id:
47
+ return "⚠️ Persistence not configured (No Dataset ID)."
48
+
49
+ try:
50
+ # Save to local temporary CSV
51
+ local_path = "temp_model_dna.csv"
52
+ self.df.to_csv(local_path, index=False)
53
+
54
+ # Upload to Hub
55
+ upload_file(
56
+ path_or_fileobj=local_path,
57
+ path_in_repo=self.csv_name,
58
+ repo_id=self.dataset_id,
59
+ repo_type="dataset",
60
+ token=self.token,
61
+ commit_message=f"Auto-save: Updated index with {len(self.df)} records"
62
+ )
63
+ return f"βœ… Saved {len(self.df)} records to {self.dataset_id}."
64
+ except Exception as e:
65
+ return f"❌ Failed to save to Hub: {e}"
66
+
67
+ def add_record(self, sha256, repo_id, filename, timestamp, tags=""):
68
+ # Check if hash already exists in our session
69
+ if not self.df.empty and sha256 in self.df['sha256'].values:
70
+ # If it exists, check timestamps to see if we found an older (original) version
71
+ existing_row = self.df[self.df['sha256'] == sha256].iloc[0]
72
+ existing_time = pd.to_datetime(existing_row['timestamp'])
73
+ new_time = pd.to_datetime(timestamp)
74
+
75
+ if new_time < existing_time:
76
+ # Update the record to the older version (The true original)
77
+ self.df.loc[self.df['sha256'] == sha256, ['repo_id', 'filename', 'timestamp', 'tags']] = [repo_id, filename, timestamp, tags]
78
+ return "updated_original"
79
+ return "duplicate"
80
+
81
+ # Add new record
82
+ new_row = pd.DataFrame([{
83
+ "sha256": sha256,
84
+ "repo_id": repo_id,
85
+ "filename": filename,
86
+ "timestamp": timestamp,
87
+ "tags": tags
88
+ }])
89
+
90
+ if self.df.empty:
91
+ self.df = new_row
92
+ else:
93
+ self.df = pd.concat([self.df, new_row], ignore_index=True)
94
+
95
+ return "added"
96
+
97
+ def search_hash(self, sha256):
98
+ if self.df.empty:
99
+ return None
100
+
101
+ sha256 = sha256.strip().lower()
102
+ match = self.df[self.df['sha256'] == sha256]
103
+
104
+ if not match.empty:
105
+ return match.iloc[0].to_dict()
106
+ return None
107
+
108
+ def get_stats(self):
109
+ return len(self.df)
110
+
111
+ # Initialize Database
112
+ db = ModelDatabase()
113
+
114
+ # --- DETECTIVE LOGIC ---
115
+
116
+ def get_repo_dna(repo_id):
117
+ """Scans a repo for LFS files and returns their hashes."""
118
+ try:
119
+ # We use model_info with files_metadata=True.
120
+ # This is the API equivalent of reading the "Raw pointer file" you found!
121
+ info = model_info(repo_id, files_metadata=True)
122
+
123
+ created_at = info.created_at if info.created_at else datetime.datetime.now()
124
+ tags = ", ".join(info.tags) if info.tags else ""
125
+
126
+ dna_list = []
127
+
128
+ # info.siblings contains the file list with metadata
129
+ if info.siblings:
130
+ for file in info.siblings:
131
+ # Check filename extension
132
+ filename = file.rfilename
133
+ is_weight_file = filename.endswith(".safetensors") or filename.endswith(".bin") or filename.endswith(".pt")
134
+
135
+ # Check if it has LFS metadata (this is the pointer file data)
136
+ if is_weight_file and file.lfs:
137
+ dna_list.append({
138
+ "sha256": file.lfs["sha256"],
139
+ "filename": filename,
140
+ "repo_id": repo_id,
141
+ "timestamp": str(created_at),
142
+ "tags": tags
143
+ })
144
+
145
+ return dna_list, None
146
+ except Exception as e:
147
+ return [], str(e)
148
+
149
+ def scan_and_index(repo_id, progress=gr.Progress()):
150
+ """Manually scan a repo and add it to the DB."""
151
+ if not repo_id:
152
+ return "⚠️ Please enter a Repository ID.", db.get_stats()
153
+
154
+ progress(0, desc=f"Connecting to {repo_id}...")
155
+ dna_list, error = get_repo_dna(repo_id)
156
+
157
+ if error:
158
+ return f"❌ Error scanning {repo_id}: {error}", db.get_stats()
159
+
160
+ if not dna_list:
161
+ return f"⚠️ No LFS weight files found in {repo_id}.", db.get_stats()
162
+
163
+ added_count = 0
164
+ updated_count = 0
165
+
166
+ progress(0.5, desc="Analyzing hashes...")
167
+ for item in dna_list:
168
+ status = db.add_record(
169
+ item['sha256'], item['repo_id'], item['filename'], item['timestamp'], item['tags']
170
+ )
171
+ if status == "added":
172
+ added_count += 1
173
+ elif status == "updated_original":
174
+ updated_count += 1
175
+
176
+ # Auto-save after indexing
177
+ save_msg = ""
178
+ if db.dataset_id:
179
+ save_msg = db.save_to_hub()
180
+
181
+ return f"βœ… Scanned {repo_id}.\nπŸ†• Added {added_count} new hashes.\nπŸ”„ Updated {updated_count} originals.\nπŸ’Ύ {save_msg}", db.get_stats()
182
+
183
+ def scan_org(org_id, limit=20, progress=gr.Progress()):
184
+ """Scans multiple models from a specific user or organization."""
185
+ if not org_id:
186
+ return "⚠️ Please enter an Organization or User ID.", db.get_stats()
187
+
188
+ progress(0, desc=f"Fetching top {limit} models for {org_id}...")
189
+ try:
190
+ # Fetch models sorted by downloads to get the most important ones first
191
+ models = list(list_models(author=org_id, sort="downloads", direction=-1, limit=limit))
192
+ except Exception as e:
193
+ return f"❌ Error fetching models for {org_id}: {e}", db.get_stats()
194
+
195
+ if not models:
196
+ return f"⚠️ No models found for {org_id}.", db.get_stats()
197
+
198
+ total_added = 0
199
+ total_updated = 0
200
+
201
+ for i, model in enumerate(models):
202
+ repo_id = model.modelId
203
+ progress((i / len(models)), desc=f"Scanning {repo_id}...")
204
+
205
+ dna_list, error = get_repo_dna(repo_id)
206
+
207
+ if error:
208
+ continue # Skip errors in bulk mode to keep going
209
+
210
+ if not dna_list:
211
+ continue
212
+
213
+ for item in dna_list:
214
+ status = db.add_record(
215
+ item['sha256'], item['repo_id'], item['filename'], item['timestamp'], item['tags']
216
+ )
217
+ if status == "added":
218
+ total_added += 1
219
+ elif status == "updated_original":
220
+ total_updated += 1
221
+
222
+ # Auto-save after indexing
223
+ save_msg = ""
224
+ if db.dataset_id:
225
+ save_msg = db.save_to_hub()
226
+
227
+ return f"βœ… Bulk Scan Complete for {org_id}.\nChecked {len(models)} models.\nπŸ†• Added {total_added} new hashes.\nπŸ”„ Updated {total_updated} originals.\nπŸ’Ύ {save_msg}", db.get_stats()
228
+
229
+ def patrol_new_uploads(limit=10, progress=gr.Progress()):
230
+ """The 'Watchdog': Scans the latest models tagged with 'safetensors'."""
231
+ progress(0, desc="Fetching latest Safetensors models...")
232
+
233
+ # 1. Fetch latest models
234
+ try:
235
+ models = list_models(filter="safetensors", sort="createdAt", direction=-1, limit=limit)
236
+ models = list(models)
237
+ except Exception as e:
238
+ return f"Error fetching models: {e}", ""
239
+
240
+ log_results = []
241
+
242
+ for i, model in enumerate(models):
243
+ repo_id = model.modelId
244
+ progress((i / len(models)), desc=f"Checking {repo_id}...")
245
+
246
+ dna_list, error = get_repo_dna(repo_id)
247
+ if error or not dna_list:
248
+ continue
249
+
250
+ for item in dna_list:
251
+ # CHECK THE DB
252
+ existing = db.search_hash(item['sha256'])
253
+
254
+ if existing:
255
+ # We found a match!
256
+ original_repo = existing['repo_id']
257
+
258
+ # If the current repo is NOT the original
259
+ if original_repo != repo_id:
260
+
261
+ # Dark Mode Friendly HTML
262
+ log = f"""
263
+ <div style="background-color: rgba(255, 82, 82, 0.15); border: 1px solid rgba(255, 82, 82, 0.5); padding: 10px; margin-bottom: 10px; border-radius: 5px; color: #ffcdd2;">
264
+ <strong>🚨 MATCH FOUND</strong><br>
265
+ New Upload: <b>{repo_id}</b><br>
266
+ Matches Hash: <code>{item['sha256'][:10]}...</code><br>
267
+ Likely Original: <a href='https://huggingface.co/{original_repo}' target='_blank' style='color: #ef9a9a;'><b>{original_repo}</b></a>
268
+ </div>
269
+ """
270
+ log_results.append(log)
271
+ else:
272
+ # If unknown, we add it to DB so it becomes the "first seen"
273
+ db.add_record(item['sha256'], item['repo_id'], item['filename'], item['timestamp'], item['tags'])
274
+
275
+ # Auto-save after patrol
276
+ if db.dataset_id:
277
+ db.save_to_hub()
278
+
279
+ if not log_results:
280
+ return "βœ… No obvious copies found in the last batch.", db.get_stats()
281
+
282
+ return "".join(log_results), db.get_stats()
283
+
284
+ def check_hash_manually(sha_input):
285
+ """User pastes a hash to search."""
286
+ if not sha_input:
287
+ return "⚠️ Please enter a SHA256 hash."
288
+
289
+ result = db.search_hash(sha_input)
290
+ if result:
291
+ # Dark Mode Friendly HTML
292
+ return f"""
293
+ <div style="background-color: rgba(76, 175, 80, 0.15); padding: 20px; border-radius: 10px; border: 1px solid rgba(76, 175, 80, 0.5); color: #c8e6c9;">
294
+ <h3>βœ… Hash Found in Index</h3>
295
+ <p><strong>Original Repo:</strong> <a href="https://huggingface.co/{result['repo_id']}" target="_blank" style="color: #a5d6a7;">{result['repo_id']}</a></p>
296
+ <p><strong>Filename:</strong> {result['filename']}</p>
297
+ <p><strong>First Seen:</strong> {result['timestamp']}</p>
298
+ </div>
299
+ """
300
+ else:
301
+ # Dark Mode Friendly HTML
302
+ return f"""
303
+ <div style="background-color: rgba(255, 152, 0, 0.15); padding: 20px; border-radius: 10px; border: 1px solid rgba(255, 152, 0, 0.5); color: #ffe0b2;">
304
+ <h3>❓ Hash Not Found</h3>
305
+ <p>This hash is not in our <strong>current session index</strong>.</p>
306
+ <p><em>Since we are not saving data, you must index a repository (like the original model source) or run a patrol first to populate the database.</em></p>
307
+ </div>
308
+ """
309
+
310
+ def configure_persistence(dataset_id, token):
311
+ return db.connect_to_hub(dataset_id, token), db.get_stats()
312
+
313
+ # --- GRADIO UI ---
314
+ # Added js to force dark mode on body load
315
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="gray", neutral_hue="gray"), title="HF Model Detective", js="document.body.classList.add('dark')") as demo:
316
+ gr.Markdown("# πŸ•΅οΈ Hugging Face Model Detective")
317
+ gr.Markdown("Identify the original source of model weights using LFS SHA256 hashes.")
318
+
319
+ with gr.Row():
320
+ stats_box = gr.Textbox(label="Hashes in Memory", value=db.get_stats(), interactive=False)
321
+
322
+ with gr.Tabs():
323
+
324
+ # TAB 1: PERSISTENCE (Configuration)
325
+ with gr.Tab("☁️ Persistence Settings"):
326
+ gr.Markdown("Connect a **Hugging Face Dataset** to save your findings permanently. The app will sync `model_dna.csv` with this dataset.")
327
+
328
+ with gr.Row():
329
+ dataset_input = gr.Textbox(label="Dataset ID", value="SHA-index/model-dna-index", placeholder="username/my-hash-dataset")
330
+ token_input = gr.Textbox(label="HF Token (Write Access)", type="password", placeholder="hf_...")
331
+
332
+ connect_btn = gr.Button("Connect & Load Data")
333
+ status_box = gr.Textbox(label="Connection Status")
334
+
335
+ connect_btn.click(configure_persistence, inputs=[dataset_input, token_input], outputs=[status_box, stats_box])
336
+
337
+ # TAB 2: INDEXING ZONE
338
+ with gr.Tab("πŸ’Ύ Indexing Zone"):
339
+ gr.Markdown("Grow the 'Truth Database' by indexing models.")
340
+
341
+ with gr.Row():
342
+ # LEFT COLUMN: Single Repo
343
+ with gr.Column():
344
+ gr.Markdown("### πŸ” Single Repository")
345
+ repo_input = gr.Textbox(label="Repository ID", placeholder="e.g. mistralai/Mistral-7B-v0.1")
346
+ scan_btn = gr.Button("Scan & Index")
347
+
348
+ # RIGHT COLUMN: Bulk Org
349
+ with gr.Column():
350
+ gr.Markdown("### 🏒 Bulk Organization/User")
351
+ org_input = gr.Textbox(label="Org/User ID", placeholder="e.g. meta-llama, google, TheBloke")
352
+ limit_slider = gr.Slider(minimum=10, maximum=100, value=20, step=10, label="Max Models to Scan")
353
+ bulk_btn = gr.Button("Bulk Scan & Index", variant="primary")
354
+
355
+ scan_log = gr.Textbox(label="Scan Log", lines=5)
356
+
357
+ # Button Logic
358
+ scan_btn.click(scan_and_index, inputs=repo_input, outputs=[scan_log, stats_box])
359
+ bulk_btn.click(scan_org, inputs=[org_input, limit_slider], outputs=[scan_log, stats_box])
360
+
361
+ # TAB 3: SEARCH
362
+ with gr.Tab("πŸ” Search by Hash"):
363
+ hash_input = gr.Textbox(label="SHA256 Hash", placeholder="Paste the SHA256 string here...")
364
+ search_btn = gr.Button("Trace Origin", variant="primary")
365
+ search_output = gr.HTML()
366
+ search_btn.click(check_hash_manually, inputs=hash_input, outputs=search_output)
367
+
368
+ # TAB 4: PATROL
369
+ with gr.Tab("🚨 Live Patrol"):
370
+ gr.Markdown("Scan the most recently uploaded models and check if they match any hashes currently in memory.")
371
+
372
+ with gr.Row():
373
+ limit_slider_patrol = gr.Slider(minimum=5, maximum=50, value=10, step=5, label="Models to Check")
374
+ patrol_btn = gr.Button("Run Patrol", variant="stop")
375
+
376
+ patrol_output = gr.HTML(label="Suspicious Findings")
377
+
378
+ patrol_btn.click(patrol_new_uploads, inputs=limit_slider_patrol, outputs=[patrol_output, stats_box])
379
+
380
+ gr.Markdown("""
381
+ ### How it works
382
+ 1. **Index:** We extract the SHA256 hash from the Git LFS pointer files (no huge downloads!).
383
+ 2. **Compare:** We check if that hash was previously seen in an older repository.
384
+ 3. **Detect:** If a new repo has the exact same hash as an old repo, it's a re-upload.
385
+ """)
386
+
387
+ if __name__ == "__main__":
388
+ demo.launch()