awacke1 commited on
Commit
d79f8d4
1 Parent(s): 70a4903

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -36
app.py CHANGED
@@ -249,23 +249,21 @@ def push_to_github(local_path, repo, github_token):
249
  origin.push(refspec=f'{current_branch}:{current_branch}')
250
 
251
 
252
-
253
- def save_or_clone_to_cosmos_db(container, query=None, response=None, clone_id=None):
254
  def generate_complex_unique_id():
255
  timestamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
256
  random_component = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=8))
257
  return f"{timestamp}-{random_component}-{str(uuid.uuid4())}"
258
 
259
  max_retries = 10
260
- base_delay = 0.1 # 100 ms
261
 
262
  for attempt in range(max_retries):
263
  try:
264
  new_id = generate_complex_unique_id()
265
-
266
  if clone_id:
267
  try:
268
-
269
  existing_doc = container.read_item(item=clone_id, partition_key=clone_id)
270
  new_doc = {
271
  'id': new_id,
@@ -275,44 +273,28 @@ def save_or_clone_to_cosmos_db(container, query=None, response=None, clone_id=No
275
  'cloned_at': datetime.utcnow().isoformat()
276
  }
277
  except exceptions.CosmosResourceNotFoundError:
278
- st.error(f"Document with ID {clone_id} not found for cloning.")
279
- return None
280
  else:
281
- new_doc = {
282
- 'id': new_id,
283
- 'query': query,
284
- 'response': response,
285
- 'created_at': datetime.utcnow().isoformat()
286
- }
287
-
288
- # Attempt to create the item
289
  response = container.create_item(body=new_doc)
290
-
291
- st.success(f"{'Cloned' if clone_id else 'New'} document saved successfully with ID: {response['id']}")
292
-
293
- # Refresh the documents in the session state
294
- st.session_state.documents = list(container.query_items(
295
- query="SELECT * FROM c ORDER BY c._ts DESC",
296
- enable_cross_partition_query=True
297
- ))
298
-
299
- return response['id']
300
 
301
  except exceptions.CosmosHttpResponseError as e:
302
- if e.status_code == 409: # Conflict error
303
  delay = base_delay * (2 ** attempt) + random.uniform(0, 0.1)
304
- st.warning(f"ID conflict occurred. Retrying in {delay:.2f} seconds... (Attempt {attempt + 1})")
305
  time.sleep(delay)
306
- else:
307
- st.error(f"Error saving to Cosmos DB: {e}")
308
- return None
309
-
310
  except Exception as e:
311
- st.error(f"An unexpected error occurred: {str(e)}")
312
- return None
313
-
314
- st.error("Failed to save document after maximum retries.")
315
- return None
316
 
317
 
318
  # 📦 Archive current container - Packing up data like you're moving to a new digital house
 
249
  origin.push(refspec=f'{current_branch}:{current_branch}')
250
 
251
 
252
+ def save_or_clone_to_cosmos_db(container, document=None, clone_id=None):
 
253
  def generate_complex_unique_id():
254
  timestamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
255
  random_component = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=8))
256
  return f"{timestamp}-{random_component}-{str(uuid.uuid4())}"
257
 
258
  max_retries = 10
259
+ base_delay = 0.1
260
 
261
  for attempt in range(max_retries):
262
  try:
263
  new_id = generate_complex_unique_id()
264
+
265
  if clone_id:
266
  try:
 
267
  existing_doc = container.read_item(item=clone_id, partition_key=clone_id)
268
  new_doc = {
269
  'id': new_id,
 
273
  'cloned_at': datetime.utcnow().isoformat()
274
  }
275
  except exceptions.CosmosResourceNotFoundError:
276
+ return False, f"Document with ID {clone_id} not found for cloning."
 
277
  else:
278
+ if document is None:
279
+ return False, "No document provided for saving"
280
+
281
+ document['id'] = new_id
282
+ document['created_at'] = datetime.utcnow().isoformat()
283
+ new_doc = document
284
+
 
285
  response = container.create_item(body=new_doc)
286
+ return True, f"{'Cloned' if clone_id else 'New'} document saved successfully with ID: {response['id']}"
 
 
 
 
 
 
 
 
 
287
 
288
  except exceptions.CosmosHttpResponseError as e:
289
+ if e.status_code == 409:
290
  delay = base_delay * (2 ** attempt) + random.uniform(0, 0.1)
 
291
  time.sleep(delay)
292
+ continue
293
+ return False, f"Error saving to Cosmos DB: {str(e)}"
 
 
294
  except Exception as e:
295
+ return False, f"An unexpected error occurred: {str(e)}"
296
+
297
+ return False, "Failed to save document after maximum retries."
 
 
298
 
299
 
300
  # 📦 Archive current container - Packing up data like you're moving to a new digital house