rahul7star commited on
Commit
8b0267d
·
verified ·
1 Parent(s): 9b16b01

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -11
app.py CHANGED
@@ -57,25 +57,36 @@ UPLOADS_DIR.mkdir(parents=True, exist_ok=True)
57
  CONTENT_DIR.mkdir(exist_ok=True)
58
  init_db()
59
 
60
- _force_reseed = bool(os.getenv("FORCE_RESEED"))
 
 
 
61
  if _force_reseed and DB_PATH.exists():
62
  print("[startup] FORCE_RESEED=1 — deleting existing DB and reseeding")
63
  DB_PATH.unlink()
64
  init_db()
65
 
66
  _gc = get_captures
 
67
  if _force_reseed or len(_gc(limit=1)) == 0:
68
  try:
69
  import seed
70
  seed.run()
71
  except Exception as e:
72
  print(f"[seed] {e}")
 
73
  else:
74
  try:
75
  import sqlite3 as _sqlite3
 
 
 
76
 
77
  all_embs = get_all_embeddings()
78
 
 
 
 
79
  for cid, emb_row in all_embs:
80
  related = find_related(
81
  emb_row,
@@ -86,7 +97,10 @@ else:
86
  with _sqlite3.connect(DB_PATH) as _conn:
87
  _conn.execute(
88
  "UPDATE captures SET related_ids=? WHERE id=?",
89
- (json.dumps(related), cid)
 
 
 
90
  )
91
 
92
  print(
@@ -94,7 +108,9 @@ else:
94
  f"({len(all_embs)} captures)"
95
  )
96
 
97
- # Export embeddings to .pt
 
 
98
  ids = []
99
  vectors = []
100
 
@@ -107,26 +123,98 @@ else:
107
  vectors.append(emb)
108
 
109
  if vectors:
110
- pt_path = CONTENT_DIR / "knowledge.pt"
 
 
 
 
 
 
 
 
 
111
 
112
  torch.save(
113
  {
 
114
  "embed_model": EMBED_MODEL,
115
- "ids": ids,
116
- "embeddings": torch.tensor(
117
- vectors,
118
- dtype=torch.float32
119
- ),
120
  "count": len(ids),
 
 
121
  },
122
  pt_path,
123
  )
124
 
125
  print(
126
- f"[startup] exported "
127
- f"{len(ids)} embeddings -> {pt_path}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  )
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  except Exception as e:
131
  print(f"[startup backfill] {e}")
132
 
 
57
  CONTENT_DIR.mkdir(exist_ok=True)
58
  init_db()
59
 
60
+ _force_reseed = os.getenv("FORCE_RESEED", "").lower() in (
61
+ "1", "true", "yes"
62
+ )
63
+
64
  if _force_reseed and DB_PATH.exists():
65
  print("[startup] FORCE_RESEED=1 — deleting existing DB and reseeding")
66
  DB_PATH.unlink()
67
  init_db()
68
 
69
  _gc = get_captures
70
+
71
  if _force_reseed or len(_gc(limit=1)) == 0:
72
  try:
73
  import seed
74
  seed.run()
75
  except Exception as e:
76
  print(f"[seed] {e}")
77
+
78
  else:
79
  try:
80
  import sqlite3 as _sqlite3
81
+ import torch
82
+ import faiss
83
+ import numpy as np
84
 
85
  all_embs = get_all_embeddings()
86
 
87
+ # --------------------------------------------------
88
+ # Existing related_ids backfill
89
+ # --------------------------------------------------
90
  for cid, emb_row in all_embs:
91
  related = find_related(
92
  emb_row,
 
97
  with _sqlite3.connect(DB_PATH) as _conn:
98
  _conn.execute(
99
  "UPDATE captures SET related_ids=? WHERE id=?",
100
+ (
101
+ json.dumps(related),
102
+ cid
103
+ )
104
  )
105
 
106
  print(
 
108
  f"({len(all_embs)} captures)"
109
  )
110
 
111
+ # --------------------------------------------------
112
+ # Build knowledge.pt + knowledge.faiss
113
+ # --------------------------------------------------
114
  ids = []
115
  vectors = []
116
 
 
123
  vectors.append(emb)
124
 
125
  if vectors:
126
+
127
+ embeddings = torch.tensor(
128
+ vectors,
129
+ dtype=torch.float32
130
+ )
131
+
132
+ # ----------------------------------------------
133
+ # knowledge.pt
134
+ # ----------------------------------------------
135
+ pt_path = UPLOADS_DIR / "knowledge.pt"
136
 
137
  torch.save(
138
  {
139
+ "version": 1,
140
  "embed_model": EMBED_MODEL,
 
 
 
 
 
141
  "count": len(ids),
142
+ "ids": ids,
143
+ "embeddings": embeddings,
144
  },
145
  pt_path,
146
  )
147
 
148
  print(
149
+ f"[startup] knowledge.pt created "
150
+ f"({len(ids)} vectors)"
151
+ )
152
+
153
+ # ----------------------------------------------
154
+ # knowledge.faiss
155
+ # ----------------------------------------------
156
+ faiss_path = UPLOADS_DIR / "knowledge.faiss"
157
+
158
+ vectors_np = (
159
+ embeddings
160
+ .cpu()
161
+ .numpy()
162
+ .astype(np.float32)
163
+ )
164
+
165
+ # cosine similarity search
166
+ faiss.normalize_L2(vectors_np)
167
+
168
+ dimension = vectors_np.shape[1]
169
+
170
+ index = faiss.IndexFlatIP(dimension)
171
+
172
+ index.add(vectors_np)
173
+
174
+ faiss.write_index(
175
+ index,
176
+ str(faiss_path)
177
+ )
178
+
179
+ print(
180
+ f"[startup] knowledge.faiss created "
181
+ f"({index.ntotal} vectors)"
182
  )
183
 
184
+ # ----------------------------------------------
185
+ # Optional Hugging Face upload
186
+ # ----------------------------------------------
187
+ if os.getenv("HF_UPLOAD_EXPORTS", "").lower() in (
188
+ "1",
189
+ "true",
190
+ "yes",
191
+ ):
192
+ from huggingface_hub import upload_file
193
+
194
+ repo_id = os.getenv("HF_EXPORT_REPO")
195
+
196
+ if repo_id:
197
+ upload_file(
198
+ path_or_fileobj=str(pt_path),
199
+ path_in_repo="knowledge.pt",
200
+ repo_id=repo_id,
201
+ repo_type="dataset",
202
+ token=os.getenv("HF_TOKEN"),
203
+ )
204
+
205
+ upload_file(
206
+ path_or_fileobj=str(faiss_path),
207
+ path_in_repo="knowledge.faiss",
208
+ repo_id=repo_id,
209
+ repo_type="dataset",
210
+ token=os.getenv("HF_TOKEN"),
211
+ )
212
+
213
+ print(
214
+ f"[startup] uploaded exports "
215
+ f"to {repo_id}"
216
+ )
217
+
218
  except Exception as e:
219
  print(f"[startup backfill] {e}")
220