siddhartharya commited on
Commit
00cf45f
β€’
1 Parent(s): 35f5bd8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +474 -462
app.py CHANGED
@@ -233,7 +233,7 @@ Category: [One category]
233
  return len(text) / 4 # Approximate token estimation
234
 
235
  prompt_tokens = estimate_tokens(prompt)
236
- max_tokens = 150 # Reduced from 200
237
  total_tokens = prompt_tokens + max_tokens
238
 
239
  # Calculate required delay
@@ -303,341 +303,350 @@ Category: [One category]
303
  bookmark['category'] = 'Uncategorized'
304
  break # Exit the retry loop on other exceptions
305
 
306
- def parse_bookmarks(file_content):
307
- """
308
- Parse bookmarks from HTML file.
309
- """
310
- logger.info("Parsing bookmarks")
311
- try:
312
- soup = BeautifulSoup(file_content, 'html.parser')
313
- extracted_bookmarks = []
314
- for link in soup.find_all('a'):
315
- url = link.get('href')
316
- title = link.text.strip()
317
- if url and title:
318
- if url.startswith('http://') or url.startswith('https://'):
319
- extracted_bookmarks.append({'url': url, 'title': title})
320
- else:
321
- logger.info(f"Skipping non-http/https URL: {url}")
322
- logger.info(f"Extracted {len(extracted_bookmarks)} bookmarks")
323
- return extracted_bookmarks
324
- except Exception as e:
325
- logger.error("Error parsing bookmarks: %s", e, exc_info=True)
326
- raise
327
-
328
- def fetch_url_info(bookmark):
329
- """
330
- Fetch information about a URL.
331
- """
332
- url = bookmark['url']
333
- if url in fetch_cache:
334
- with lock:
335
- bookmark.update(fetch_cache[url])
336
- return
337
-
338
- try:
339
- logger.info(f"Fetching URL info for: {url}")
340
- headers = {
341
- 'User-Agent': 'Mozilla/5.0',
342
- 'Accept-Language': 'en-US,en;q=0.9',
343
- }
344
- response = requests.get(url, headers=headers, timeout=5, verify=False, allow_redirects=True)
345
- bookmark['etag'] = response.headers.get('ETag', 'N/A')
346
- bookmark['status_code'] = response.status_code
347
-
348
- content = response.text
349
- logger.info(f"Fetched content length for {url}: {len(content)} characters")
350
-
351
- # Handle status codes
352
- if response.status_code >= 500:
353
- # Server error, consider as dead link
354
- bookmark['dead_link'] = True
355
- bookmark['description'] = ''
356
- bookmark['html_content'] = ''
357
- logger.warning(f"Dead link detected: {url} with status {response.status_code}")
358
- else:
359
- bookmark['dead_link'] = False
360
- bookmark['html_content'] = content
361
- bookmark['description'] = ''
362
- logger.info(f"Fetched information for {url}")
363
-
364
- except requests.exceptions.Timeout:
365
- bookmark['dead_link'] = False # Mark as 'Unknown' instead of 'Dead'
366
- bookmark['etag'] = 'N/A'
367
- bookmark['status_code'] = 'Timeout'
368
- bookmark['description'] = ''
369
- bookmark['html_content'] = ''
370
- bookmark['slow_link'] = True # Custom flag to indicate slow response
371
- logger.warning(f"Timeout while fetching {url}. Marking as 'Slow'.")
372
- except Exception as e:
373
  bookmark['dead_link'] = True
374
- bookmark['etag'] = 'N/A'
375
- bookmark['status_code'] = 'Error'
376
  bookmark['description'] = ''
377
  bookmark['html_content'] = ''
378
- logger.error(f"Error fetching URL info for {url}: {e}", exc_info=True)
379
- finally:
380
- with lock:
381
- fetch_cache[url] = {
382
- 'etag': bookmark.get('etag'),
383
- 'status_code': bookmark.get('status_code'),
384
- 'dead_link': bookmark.get('dead_link'),
385
- 'description': bookmark.get('description'),
386
- 'html_content': bookmark.get('html_content', ''),
387
- 'slow_link': bookmark.get('slow_link', False),
388
- }
389
-
390
- def vectorize_and_index(bookmarks_list):
391
- """
392
- Create vector embeddings for bookmarks and build FAISS index with ID mapping.
393
- """
394
- global faiss_index
395
- logger.info("Vectorizing summaries and building FAISS index")
396
- try:
397
- summaries = [bookmark['summary'] for bookmark in bookmarks_list]
398
- embeddings = embedding_model.encode(summaries)
399
- dimension = embeddings.shape[1]
400
- index = faiss.IndexIDMap(faiss.IndexFlatL2(dimension))
401
- # Assign unique IDs to each bookmark
402
- ids = np.array([bookmark['id'] for bookmark in bookmarks_list], dtype=np.int64)
403
- index.add_with_ids(np.array(embeddings).astype('float32'), ids)
404
- faiss_index = index
405
- logger.info("FAISS index built successfully with IDs")
406
- return index
407
- except Exception as e:
408
- logger.error(f"Error in vectorizing and indexing: {e}", exc_info=True)
409
- raise
410
-
411
- def display_bookmarks():
412
- """
413
- Generate HTML display for bookmarks.
414
- """
415
- logger.info("Generating HTML display for bookmarks")
416
- cards = ''
417
- for i, bookmark in enumerate(bookmarks):
418
- index = i + 1
419
- if bookmark.get('dead_link'):
420
- status = "❌ Dead Link"
421
- card_style = "border: 2px solid red;"
422
- text_style = "color: white;" # Set font color to white
423
- elif bookmark.get('slow_link'):
424
- status = "⏳ Slow Response"
425
- card_style = "border: 2px solid orange;"
426
- text_style = "color: white;" # Set font color to white
427
- else:
428
- status = "βœ… Active"
429
- card_style = "border: 2px solid green;"
430
- text_style = "color: white;" # Set font color to white
431
-
432
- title = bookmark['title']
433
- url = bookmark['url']
434
- etag = bookmark.get('etag', 'N/A')
435
- summary = bookmark.get('summary', '')
436
- category = bookmark.get('category', 'Uncategorized')
437
-
438
- # Escape HTML content to prevent XSS attacks
439
- from html import escape
440
- title = escape(title)
441
- url = escape(url)
442
- summary = escape(summary)
443
- category = escape(category)
444
-
445
- card_html = f'''
446
- <div class="card" style="{card_style} padding: 10px; margin: 10px; border-radius: 5px; background-color: #1e1e1e;">
447
- <div class="card-content">
448
- <h3 style="{text_style}">{index}. {title} {status}</h3>
449
- <p style="{text_style}"><strong>Category:</strong> {category}</p>
450
- <p style="{text_style}"><strong>URL:</strong> <a href="{url}" target="_blank" style="{text_style}">{url}</a></p>
451
- <p style="{text_style}"><strong>ETag:</strong> {etag}</p>
452
- <p style="{text_style}"><strong>Summary:</strong> {summary}</p>
453
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
454
  </div>
455
- '''
456
- cards += card_html
457
- logger.info("HTML display generated")
458
- return cards
459
-
460
- def process_uploaded_file(file):
461
- """
462
- Process the uploaded bookmarks file.
463
- """
464
- global bookmarks, faiss_index
465
- logger.info("Processing uploaded file")
466
-
467
- if file is None:
468
- logger.warning("No file uploaded")
469
- return "Please upload a bookmarks HTML file.", '', gr.update(choices=[]), display_bookmarks()
470
 
471
- try:
472
- file_content = file.decode('utf-8')
473
- except UnicodeDecodeError as e:
474
- logger.error(f"Error decoding the file: {e}", exc_info=True)
475
- return "Error decoding the file. Please ensure it's a valid HTML file.", '', gr.update(choices=[]), display_bookmarks()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476
 
477
- try:
478
- bookmarks = parse_bookmarks(file_content)
479
- except Exception as e:
480
- logger.error(f"Error parsing bookmarks: {e}", exc_info=True)
481
- return "Error parsing the bookmarks HTML file.", '', gr.update(choices=[]), display_bookmarks()
482
 
483
- if not bookmarks:
484
- logger.warning("No bookmarks found in the uploaded file")
485
- return "No bookmarks found in the uploaded file.", '', gr.update(choices=[]), display_bookmarks()
486
 
487
- # Assign unique IDs to bookmarks
488
- for idx, bookmark in enumerate(bookmarks):
489
- bookmark['id'] = idx
490
 
491
- # Fetch bookmark info concurrently
492
- logger.info("Fetching URL info concurrently")
493
- with ThreadPoolExecutor(max_workers=3) as executor: # Adjusted max_workers to 3
494
- executor.map(fetch_url_info, bookmarks)
495
 
496
- # Process bookmarks concurrently with LLM calls
497
- logger.info("Processing bookmarks with LLM concurrently")
498
- with ThreadPoolExecutor(max_workers=1) as executor: # Adjusted max_workers to 1
499
- executor.map(generate_summary_and_assign_category, bookmarks)
500
 
501
- try:
502
- faiss_index = vectorize_and_index(bookmarks)
503
- except Exception as e:
504
- logger.error(f"Error building FAISS index: {e}", exc_info=True)
505
- return "Error building search index.", '', gr.update(choices=[]), display_bookmarks()
506
-
507
- message = f"βœ… Successfully processed {len(bookmarks)} bookmarks."
508
- logger.info(message)
509
-
510
- # Generate displays and updates
511
- bookmark_html = display_bookmarks()
512
- choices = [f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})"
513
- for i, bookmark in enumerate(bookmarks)]
514
-
515
- return message, bookmark_html, gr.update(choices=choices), bookmark_html
516
-
517
- def delete_selected_bookmarks(selected_indices):
518
- """
519
- Delete selected bookmarks and remove their vectors from the FAISS index.
520
- """
521
- global bookmarks, faiss_index
522
- if not selected_indices:
523
- return "⚠️ No bookmarks selected.", gr.update(choices=[]), display_bookmarks()
524
-
525
- ids_to_delete = []
526
- indices_to_delete = []
527
- for s in selected_indices:
528
- idx = int(s.split('.')[0]) - 1
529
- if 0 <= idx < len(bookmarks):
530
- bookmark_id = bookmarks[idx]['id']
531
- ids_to_delete.append(bookmark_id)
532
- indices_to_delete.append(idx)
533
- logger.info(f"Deleting bookmark at index {idx + 1}")
534
-
535
- # Remove vectors from FAISS index
536
- if faiss_index is not None and ids_to_delete:
537
- faiss_index.remove_ids(np.array(ids_to_delete, dtype=np.int64))
538
-
539
- # Remove bookmarks from the list (reverse order to avoid index shifting)
540
- for idx in sorted(indices_to_delete, reverse=True):
541
- bookmarks.pop(idx)
542
-
543
- message = "πŸ—‘οΈ Selected bookmarks deleted successfully."
544
- logger.info(message)
545
- choices = [f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})"
546
- for i, bookmark in enumerate(bookmarks)]
547
-
548
- return message, gr.update(choices=choices), display_bookmarks()
549
-
550
- def edit_selected_bookmarks_category(selected_indices, new_category):
551
- """
552
- Edit category of selected bookmarks.
553
- """
554
- if not selected_indices:
555
- return "⚠️ No bookmarks selected.", gr.update(choices=[]), display_bookmarks()
556
- if not new_category:
557
- return "⚠️ No new category selected.", gr.update(choices=[]), display_bookmarks()
558
-
559
- indices = [int(s.split('.')[0])-1 for s in selected_indices]
560
- for idx in indices:
561
- if 0 <= idx < len(bookmarks):
562
- bookmarks[idx]['category'] = new_category
563
- logger.info(f"Updated category for bookmark {idx + 1} to {new_category}")
564
-
565
- message = "✏️ Category updated for selected bookmarks."
566
- logger.info(message)
567
-
568
- # Update choices and display
569
- choices = [f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})"
570
- for i, bookmark in enumerate(bookmarks)]
571
-
572
- return message, gr.update(choices=choices), display_bookmarks()
573
-
574
- def export_bookmarks():
575
- """
576
- Export bookmarks to an HTML file.
577
- """
578
- if not bookmarks:
579
- logger.warning("No bookmarks to export")
580
- return None # Return None instead of a message
581
 
582
- try:
583
- logger.info("Exporting bookmarks to HTML")
584
- soup = BeautifulSoup("<!DOCTYPE NETSCAPE-Bookmark-file-1><Title>Bookmarks</Title><H1>Bookmarks</H1>", 'html.parser')
585
- dl = soup.new_tag('DL')
586
- for bookmark in bookmarks:
587
- dt = soup.new_tag('DT')
588
- a = soup.new_tag('A', href=bookmark['url'])
589
- a.string = bookmark['title']
590
- dt.append(a)
591
- dl.append(dt)
592
- soup.append(dl)
593
- html_content = str(soup)
594
- # Save to a temporary file
595
- output_file = "exported_bookmarks.html"
596
- with open(output_file, 'w', encoding='utf-8') as f:
597
- f.write(html_content)
598
- logger.info("Bookmarks exported successfully")
599
- return output_file # Return the file path
600
- except Exception as e:
601
- logger.error(f"Error exporting bookmarks: {e}", exc_info=True)
602
- return None # Return None in case of error
603
-
604
- def chatbot_response(user_query, chat_history):
605
- """
606
- Generate chatbot response using the FAISS index and embeddings, maintaining chat history.
607
- """
608
- if not bookmarks or faiss_index is None:
609
- logger.warning("No bookmarks available for chatbot")
610
- chat_history.append({"role": "assistant", "content": "⚠️ No bookmarks available. Please upload and process your bookmarks first."})
611
  return chat_history
612
 
613
- logger.info(f"Chatbot received query: {user_query}")
 
 
 
 
614
 
615
- try:
616
- # Encode the user query
617
- query_vector = embedding_model.encode([user_query]).astype('float32')
618
-
619
- # Search the FAISS index
620
- k = 5 # Number of results to return
621
- distances, ids = faiss_index.search(query_vector, k)
622
- ids = ids.flatten()
623
-
624
- # Retrieve the bookmarks
625
- id_to_bookmark = {bookmark['id']: bookmark for bookmark in bookmarks}
626
- matching_bookmarks = [id_to_bookmark.get(id) for id in ids if id in id_to_bookmark]
627
-
628
- if not matching_bookmarks:
629
- answer = "No relevant bookmarks found for your query."
630
- chat_history.append({"role": "assistant", "content": answer})
631
- return chat_history
632
-
633
- # Format the response
634
- bookmarks_info = "\n".join([
635
- f"Title: {bookmark['title']}\nURL: {bookmark['url']}\nSummary: {bookmark['summary']}"
636
- for bookmark in matching_bookmarks
637
- ])
638
-
639
- # Use the LLM via Groq Cloud API to generate a response
640
- prompt = f"""
641
  A user asked: "{user_query}"
642
  Based on the bookmarks below, provide a helpful answer to the user's query, referencing the relevant bookmarks.
643
  Bookmarks:
@@ -645,64 +654,67 @@ Bookmarks:
645
  Provide a concise and helpful response.
646
  """
647
 
648
- # Estimate tokens
649
- def estimate_tokens(text):
650
- return len(text) / 4 # Approximate token estimation
651
 
652
- prompt_tokens = estimate_tokens(prompt)
653
- max_tokens = 300 # Adjust as needed
654
- total_tokens = prompt_tokens + max_tokens
655
 
656
- # Calculate required delay
657
- tokens_per_minute = 60000 # Adjust based on your rate limit
658
- tokens_per_second = tokens_per_minute / 60
659
- required_delay = total_tokens / tokens_per_second
660
- sleep_time = max(required_delay, 1)
661
-
662
- # Acquire semaphore before making API call
663
- api_semaphore.acquire()
664
- try:
665
- # Call the LLM via Groq Cloud API
666
- response = openai.ChatCompletion.create(
667
- model='llama-3.1-70b-versatile', # Using the specified model
668
- messages=[
669
- {"role": "user", "content": prompt}
670
- ],
671
- max_tokens=int(max_tokens),
672
- temperature=0.7,
673
- )
674
- finally:
675
- # Release semaphore after API call
676
- api_semaphore.release()
677
-
678
- answer = response['choices'][0]['message']['content'].strip()
679
- logger.info("Chatbot response generated")
680
- time.sleep(sleep_time)
681
-
682
- # Append the interaction to chat history
683
- chat_history.append({"role": "assistant", "content": answer})
684
- return chat_history
685
-
686
- except openai.error.RateLimitError as e:
687
- wait_time = int(e.headers.get("Retry-After", 5))
688
- logger.warning(f"Rate limit reached. Waiting for {wait_time} seconds before retrying...")
689
- time.sleep(wait_time)
690
- return chatbot_response(user_query, chat_history) # Retry after waiting
691
- except Exception as e:
692
- error_message = f"⚠️ Error processing your query: {str(e)}"
693
- logger.error(error_message, exc_info=True)
694
- chat_history.append({"role": "assistant", "content": error_message})
695
- return chat_history
696
 
697
- def build_app():
698
- """
699
- Build and launch the Gradio app.
700
- """
701
  try:
702
- logger.info("Building Gradio app")
703
- with gr.Blocks(css="app.css") as demo:
704
- # General Overview
705
- gr.Markdown("""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
706
  # πŸ“š SmartMarks - AI Browser Bookmarks Manager
707
 
708
  Welcome to **SmartMarks**, your intelligent assistant for managing browser bookmarks. SmartMarks leverages AI to help you organize, search, and interact with your bookmarks seamlessly.
@@ -720,9 +732,9 @@ SmartMarks is divided into three main sections:
720
  Navigate through the tabs to explore each feature in detail.
721
  """)
722
 
723
- # Upload and Process Bookmarks Tab
724
- with gr.Tab("Upload and Process Bookmarks"):
725
- gr.Markdown("""
726
  ## πŸ“‚ **Upload and Process Bookmarks**
727
 
728
  ### πŸ“ **Steps to Upload and Process:**
@@ -739,20 +751,20 @@ Navigate through the tabs to explore each feature in detail.
739
  - Once processing is complete, your bookmarks will be displayed in an organized and visually appealing format below.
740
  """)
741
 
742
- upload = gr.File(label="πŸ“ Upload Bookmarks HTML File", type='binary')
743
- process_button = gr.Button("βš™οΈ Process Bookmarks")
744
- output_text = gr.Textbox(label="βœ… Output", interactive=False)
745
- bookmark_display = gr.HTML(label="πŸ“„ Processed Bookmarks")
746
 
747
- process_button.click(
748
- process_uploaded_file,
749
- inputs=upload,
750
- outputs=[output_text, bookmark_display, gr.State(), gr.State()]
751
- )
752
 
753
- # Chat with Bookmarks Tab
754
- with gr.Tab("Chat with Bookmarks"):
755
- gr.Markdown("""
756
  ## πŸ’¬ **Chat with Bookmarks**
757
 
758
  ### πŸ€– **How to Interact:**
@@ -770,22 +782,22 @@ Navigate through the tabs to explore each feature in detail.
770
  - All your queries and the corresponding AI responses are displayed in the chat history for your reference.
771
  """)
772
 
773
- chatbot = gr.Chatbot(label="πŸ’¬ Chat with SmartMarks", type='messages')
774
- user_input = gr.Textbox(
775
- label="✍️ Ask about your bookmarks",
776
- placeholder="e.g., Do I have any bookmarks about AI?"
777
- )
778
- chat_button = gr.Button("πŸ“¨ Send")
779
-
780
- chat_button.click(
781
- chatbot_response,
782
- inputs=[user_input, chatbot],
783
- outputs=chatbot
784
- )
785
-
786
- # Manage Bookmarks Tab
787
- with gr.Tab("Manage Bookmarks"):
788
- gr.Markdown("""
789
  ## πŸ› οΈ **Manage Bookmarks**
790
 
791
  ### πŸ—‚οΈ **Features:**
@@ -812,60 +824,60 @@ Navigate through the tabs to explore each feature in detail.
812
  - Click the **"πŸ”„ Refresh Bookmarks"** button to ensure the latest state is reflected in the display.
813
  """)
814
 
815
- manage_output = gr.Textbox(label="πŸ”„ Status", interactive=False)
816
- bookmark_selector = gr.CheckboxGroup(
817
- label="βœ… Select Bookmarks",
818
- choices=[]
819
- )
820
- new_category = gr.Dropdown(
821
- label="πŸ†• New Category",
822
- choices=CATEGORIES,
823
- value="Uncategorized"
824
- )
825
- bookmark_display_manage = gr.HTML(label="πŸ“„ Bookmarks")
826
-
827
- with gr.Row():
828
- delete_button = gr.Button("πŸ—‘οΈ Delete Selected")
829
- edit_category_button = gr.Button("✏️ Edit Category")
830
- export_button = gr.Button("πŸ’Ύ Export")
831
- refresh_button = gr.Button("πŸ”„ Refresh Bookmarks")
832
-
833
- download_link = gr.File(label="πŸ“₯ Download Exported Bookmarks")
834
-
835
- # Define button actions
836
- delete_button.click(
837
- delete_selected_bookmarks,
838
- inputs=bookmark_selector,
839
- outputs=[manage_output, bookmark_selector, bookmark_display_manage]
840
- )
841
-
842
- edit_category_button.click(
843
- edit_selected_bookmarks_category,
844
- inputs=[bookmark_selector, new_category],
845
- outputs=[manage_output, bookmark_selector, bookmark_display_manage]
846
- )
847
-
848
- export_button.click(
849
- export_bookmarks,
850
- outputs=download_link
851
- )
852
-
853
- refresh_button.click(
854
- lambda bookmarks: (
855
- [
856
- f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})" for i, bookmark in enumerate(bookmarks)
857
- ],
858
- display_bookmarks()
859
- ),
860
- inputs=gr.State(),
861
- outputs=[bookmark_selector, bookmark_display_manage]
862
- )
863
-
864
- logger.info("Launching Gradio app")
865
- demo.launch(debug=True)
866
- except Exception as e:
867
- logger.error(f"Error building the app: {e}", exc_info=True)
868
- print(f"Error building the app: {e}")
869
 
870
- if __name__ == "__main__":
871
- build_app()
 
233
  return len(text) / 4 # Approximate token estimation
234
 
235
  prompt_tokens = estimate_tokens(prompt)
236
+ max_tokens = 150 # Adjusted from 200
237
  total_tokens = prompt_tokens + max_tokens
238
 
239
  # Calculate required delay
 
303
  bookmark['category'] = 'Uncategorized'
304
  break # Exit the retry loop on other exceptions
305
 
306
+ def parse_bookmarks(file_content):
307
+ """
308
+ Parse bookmarks from HTML file.
309
+ """
310
+ logger.info("Parsing bookmarks")
311
+ try:
312
+ soup = BeautifulSoup(file_content, 'html.parser')
313
+ extracted_bookmarks = []
314
+ for link in soup.find_all('a'):
315
+ url = link.get('href')
316
+ title = link.text.strip()
317
+ if url and title:
318
+ if url.startswith('http://') or url.startswith('https://'):
319
+ extracted_bookmarks.append({'url': url, 'title': title})
320
+ else:
321
+ logger.info(f"Skipping non-http/https URL: {url}")
322
+ logger.info(f"Extracted {len(extracted_bookmarks)} bookmarks")
323
+ return extracted_bookmarks
324
+ except Exception as e:
325
+ logger.error("Error parsing bookmarks: %s", e, exc_info=True)
326
+ raise
327
+
328
+ def fetch_url_info(bookmark):
329
+ """
330
+ Fetch information about a URL.
331
+ """
332
+ url = bookmark['url']
333
+ if url in fetch_cache:
334
+ with lock:
335
+ bookmark.update(fetch_cache[url])
336
+ return
337
+
338
+ try:
339
+ logger.info(f"Fetching URL info for: {url}")
340
+ headers = {
341
+ 'User-Agent': 'Mozilla/5.0',
342
+ 'Accept-Language': 'en-US,en;q=0.9',
343
+ }
344
+ response = requests.get(url, headers=headers, timeout=5, verify=False, allow_redirects=True)
345
+ bookmark['etag'] = response.headers.get('ETag', 'N/A')
346
+ bookmark['status_code'] = response.status_code
347
+
348
+ content = response.text
349
+ logger.info(f"Fetched content length for {url}: {len(content)} characters")
350
+
351
+ # Handle status codes
352
+ if response.status_code >= 500:
353
+ # Server error, consider as dead link
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
  bookmark['dead_link'] = True
 
 
355
  bookmark['description'] = ''
356
  bookmark['html_content'] = ''
357
+ logger.warning(f"Dead link detected: {url} with status {response.status_code}")
358
+ else:
359
+ bookmark['dead_link'] = False
360
+ bookmark['html_content'] = content
361
+ bookmark['description'] = ''
362
+ logger.info(f"Fetched information for {url}")
363
+
364
+ except requests.exceptions.Timeout:
365
+ bookmark['dead_link'] = False # Mark as 'Unknown' instead of 'Dead'
366
+ bookmark['etag'] = 'N/A'
367
+ bookmark['status_code'] = 'Timeout'
368
+ bookmark['description'] = ''
369
+ bookmark['html_content'] = ''
370
+ bookmark['slow_link'] = True # Custom flag to indicate slow response
371
+ logger.warning(f"Timeout while fetching {url}. Marking as 'Slow'.")
372
+ except Exception as e:
373
+ bookmark['dead_link'] = True
374
+ bookmark['etag'] = 'N/A'
375
+ bookmark['status_code'] = 'Error'
376
+ bookmark['description'] = ''
377
+ bookmark['html_content'] = ''
378
+ logger.error(f"Error fetching URL info for {url}: {e}", exc_info=True)
379
+ finally:
380
+ with lock:
381
+ fetch_cache[url] = {
382
+ 'etag': bookmark.get('etag'),
383
+ 'status_code': bookmark.get('status_code'),
384
+ 'dead_link': bookmark.get('dead_link'),
385
+ 'description': bookmark.get('description'),
386
+ 'html_content': bookmark.get('html_content', ''),
387
+ 'slow_link': bookmark.get('slow_link', False),
388
+ }
389
+
390
+ def vectorize_and_index(bookmarks_list):
391
+ """
392
+ Create vector embeddings for bookmarks and build FAISS index with ID mapping.
393
+ """
394
+ global faiss_index
395
+ logger.info("Vectorizing summaries and building FAISS index")
396
+ try:
397
+ summaries = [bookmark['summary'] for bookmark in bookmarks_list]
398
+ embeddings = embedding_model.encode(summaries)
399
+ dimension = embeddings.shape[1]
400
+ index = faiss.IndexIDMap(faiss.IndexFlatL2(dimension))
401
+ # Assign unique IDs to each bookmark
402
+ ids = np.array([bookmark['id'] for bookmark in bookmarks_list], dtype=np.int64)
403
+ index.add_with_ids(np.array(embeddings).astype('float32'), ids)
404
+ faiss_index = index
405
+ logger.info("FAISS index built successfully with IDs")
406
+ return index
407
+ except Exception as e:
408
+ logger.error(f"Error in vectorizing and indexing: {e}", exc_info=True)
409
+ raise
410
+
411
+ def display_bookmarks():
412
+ """
413
+ Generate HTML display for bookmarks.
414
+ """
415
+ logger.info("Generating HTML display for bookmarks")
416
+ cards = ''
417
+ for i, bookmark in enumerate(bookmarks):
418
+ index = i + 1
419
+ if bookmark.get('dead_link'):
420
+ status = "❌ Dead Link"
421
+ card_style = "border: 2px solid red;"
422
+ text_style = "color: white;" # Set font color to white
423
+ elif bookmark.get('slow_link'):
424
+ status = "⏳ Slow Response"
425
+ card_style = "border: 2px solid orange;"
426
+ text_style = "color: white;" # Set font color to white
427
+ else:
428
+ status = "βœ… Active"
429
+ card_style = "border: 2px solid green;"
430
+ text_style = "color: white;" # Set font color to white
431
+
432
+ title = bookmark['title']
433
+ url = bookmark['url']
434
+ etag = bookmark.get('etag', 'N/A')
435
+ summary = bookmark.get('summary', '')
436
+ category = bookmark.get('category', 'Uncategorized')
437
+
438
+ # Escape HTML content to prevent XSS attacks
439
+ from html import escape
440
+ title = escape(title)
441
+ url = escape(url)
442
+ summary = escape(summary)
443
+ category = escape(category)
444
+
445
+ card_html = f'''
446
+ <div class="card" style="{card_style} padding: 10px; margin: 10px; border-radius: 5px; background-color: #1e1e1e;">
447
+ <div class="card-content">
448
+ <h3 style="{text_style}">{index}. {title} {status}</h3>
449
+ <p style="{text_style}"><strong>Category:</strong> {category}</p>
450
+ <p style="{text_style}"><strong>URL:</strong> <a href="{url}" target="_blank" style="{text_style}">{url}</a></p>
451
+ <p style="{text_style}"><strong>ETag:</strong> {etag}</p>
452
+ <p style="{text_style}"><strong>Summary:</strong> {summary}</p>
453
  </div>
454
+ </div>
455
+ '''
456
+ cards += card_html
457
+ logger.info("HTML display generated")
458
+ return cards
 
 
 
 
 
 
 
 
 
 
459
 
460
+ def process_uploaded_file(file, state_bookmarks):
461
+ """
462
+ Process the uploaded bookmarks file.
463
+ """
464
+ global bookmarks, faiss_index
465
+ logger.info("Processing uploaded file")
466
+
467
+ if file is None:
468
+ logger.warning("No file uploaded")
469
+ return "Please upload a bookmarks HTML file.", '', state_bookmarks, display_bookmarks()
470
+
471
+ try:
472
+ file_content = file.decode('utf-8')
473
+ except UnicodeDecodeError as e:
474
+ logger.error(f"Error decoding the file: {e}", exc_info=True)
475
+ return "Error decoding the file. Please ensure it's a valid HTML file.", '', state_bookmarks, display_bookmarks()
476
+
477
+ try:
478
+ bookmarks = parse_bookmarks(file_content)
479
+ except Exception as e:
480
+ logger.error(f"Error parsing bookmarks: {e}", exc_info=True)
481
+ return "Error parsing the bookmarks HTML file.", '', state_bookmarks, display_bookmarks()
482
+
483
+ if not bookmarks:
484
+ logger.warning("No bookmarks found in the uploaded file")
485
+ return "No bookmarks found in the uploaded file.", '', state_bookmarks, display_bookmarks()
486
+
487
+ # Assign unique IDs to bookmarks
488
+ for idx, bookmark in enumerate(bookmarks):
489
+ bookmark['id'] = idx
490
+
491
+ # Fetch bookmark info concurrently
492
+ logger.info("Fetching URL info concurrently")
493
+ with ThreadPoolExecutor(max_workers=3) as executor: # Adjusted max_workers to 3
494
+ executor.map(fetch_url_info, bookmarks)
495
+
496
+ # Process bookmarks concurrently with LLM calls
497
+ logger.info("Processing bookmarks with LLM concurrently")
498
+ with ThreadPoolExecutor(max_workers=1) as executor: # Adjusted max_workers to 1
499
+ executor.map(generate_summary_and_assign_category, bookmarks)
500
+
501
+ try:
502
+ faiss_index = vectorize_and_index(bookmarks)
503
+ except Exception as e:
504
+ logger.error(f"Error building FAISS index: {e}", exc_info=True)
505
+ return "Error building search index.", '', state_bookmarks, display_bookmarks()
506
+
507
+ message = f"βœ… Successfully processed {len(bookmarks)} bookmarks."
508
+ logger.info(message)
509
+
510
+ # Generate displays and updates
511
+ bookmark_html = display_bookmarks()
512
+ choices = [f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})"
513
+ for i, bookmark in enumerate(bookmarks)]
514
+
515
+ # Update state
516
+ state_bookmarks = bookmarks.copy()
517
+
518
+ return message, bookmark_html, state_bookmarks, bookmark_html
519
+
520
+ def delete_selected_bookmarks(selected_indices, state_bookmarks):
521
+ """
522
+ Delete selected bookmarks and remove their vectors from the FAISS index.
523
+ """
524
+ global bookmarks, faiss_index
525
+ if not selected_indices:
526
+ return "⚠️ No bookmarks selected.", gr.update(choices=[]), display_bookmarks()
527
+
528
+ ids_to_delete = []
529
+ indices_to_delete = []
530
+ for s in selected_indices:
531
+ idx = int(s.split('.')[0]) - 1
532
+ if 0 <= idx < len(bookmarks):
533
+ bookmark_id = bookmarks[idx]['id']
534
+ ids_to_delete.append(bookmark_id)
535
+ indices_to_delete.append(idx)
536
+ logger.info(f"Deleting bookmark at index {idx + 1}")
537
+
538
+ # Remove vectors from FAISS index
539
+ if faiss_index is not None and ids_to_delete:
540
+ faiss_index.remove_ids(np.array(ids_to_delete, dtype=np.int64))
541
+
542
+ # Remove bookmarks from the list (reverse order to avoid index shifting)
543
+ for idx in sorted(indices_to_delete, reverse=True):
544
+ bookmarks.pop(idx)
545
+
546
+ message = "πŸ—‘οΈ Selected bookmarks deleted successfully."
547
+ logger.info(message)
548
+ choices = [f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})"
549
+ for i, bookmark in enumerate(bookmarks)]
550
+
551
+ # Update state
552
+ state_bookmarks = bookmarks.copy()
553
+
554
+ return message, gr.update(choices=choices), display_bookmarks()
555
+
556
+ def edit_selected_bookmarks_category(selected_indices, new_category, state_bookmarks):
557
+ """
558
+ Edit category of selected bookmarks.
559
+ """
560
+ if not selected_indices:
561
+ return "⚠️ No bookmarks selected.", gr.update(choices=[]), display_bookmarks(), state_bookmarks
562
+ if not new_category:
563
+ return "⚠️ No new category selected.", gr.update(choices=[]), display_bookmarks(), state_bookmarks
564
 
565
+ indices = [int(s.split('.')[0])-1 for s in selected_indices]
566
+ for idx in indices:
567
+ if 0 <= idx < len(bookmarks):
568
+ bookmarks[idx]['category'] = new_category
569
+ logger.info(f"Updated category for bookmark {idx + 1} to {new_category}")
570
 
571
+ message = "✏️ Category updated for selected bookmarks."
572
+ logger.info(message)
 
573
 
574
+ # Update choices and display
575
+ choices = [f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})"
576
+ for i, bookmark in enumerate(bookmarks)]
577
 
578
+ # Update state
579
+ state_bookmarks = bookmarks.copy()
 
 
580
 
581
+ return message, gr.update(choices=choices), display_bookmarks(), state_bookmarks
 
 
 
582
 
583
+ def export_bookmarks():
584
+ """
585
+ Export bookmarks to an HTML file.
586
+ """
587
+ if not bookmarks:
588
+ logger.warning("No bookmarks to export")
589
+ return None # Return None instead of a message
590
+
591
+ try:
592
+ logger.info("Exporting bookmarks to HTML")
593
+ soup = BeautifulSoup("<!DOCTYPE NETSCAPE-Bookmark-file-1><Title>Bookmarks</Title><H1>Bookmarks</H1>", 'html.parser')
594
+ dl = soup.new_tag('DL')
595
+ for bookmark in bookmarks:
596
+ dt = soup.new_tag('DT')
597
+ a = soup.new_tag('A', href=bookmark['url'])
598
+ a.string = bookmark['title']
599
+ dt.append(a)
600
+ dl.append(dt)
601
+ soup.append(dl)
602
+ html_content = str(soup)
603
+ # Save to a temporary file
604
+ output_file = "exported_bookmarks.html"
605
+ with open(output_file, 'w', encoding='utf-8') as f:
606
+ f.write(html_content)
607
+ logger.info("Bookmarks exported successfully")
608
+ return output_file # Return the file path
609
+ except Exception as e:
610
+ logger.error(f"Error exporting bookmarks: {e}", exc_info=True)
611
+ return None # Return None in case of error
612
+
613
+ def chatbot_response(user_query, chat_history):
614
+ """
615
+ Generate chatbot response using the FAISS index and embeddings, maintaining chat history.
616
+ """
617
+ if not bookmarks or faiss_index is None:
618
+ logger.warning("No bookmarks available for chatbot")
619
+ chat_history.append({"role": "assistant", "content": "⚠️ No bookmarks available. Please upload and process your bookmarks first."})
620
+ return chat_history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
621
 
622
+ logger.info(f"Chatbot received query: {user_query}")
623
+
624
+ try:
625
+ # Encode the user query
626
+ query_vector = embedding_model.encode([user_query]).astype('float32')
627
+
628
+ # Search the FAISS index
629
+ k = 5 # Number of results to return
630
+ distances, ids = faiss_index.search(query_vector, k)
631
+ ids = ids.flatten()
632
+
633
+ # Retrieve the bookmarks
634
+ id_to_bookmark = {bookmark['id']: bookmark for bookmark in bookmarks}
635
+ matching_bookmarks = [id_to_bookmark.get(id) for id in ids if id in id_to_bookmark]
636
+
637
+ if not matching_bookmarks:
638
+ answer = "No relevant bookmarks found for your query."
639
+ chat_history.append({"role": "assistant", "content": answer})
 
 
 
 
 
 
 
 
 
 
 
640
  return chat_history
641
 
642
+ # Format the response
643
+ bookmarks_info = "\n".join([
644
+ f"Title: {bookmark['title']}\nURL: {bookmark['url']}\nSummary: {bookmark['summary']}"
645
+ for bookmark in matching_bookmarks
646
+ ])
647
 
648
+ # Use the LLM via Groq Cloud API to generate a response
649
+ prompt = f"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
650
  A user asked: "{user_query}"
651
  Based on the bookmarks below, provide a helpful answer to the user's query, referencing the relevant bookmarks.
652
  Bookmarks:
 
654
  Provide a concise and helpful response.
655
  """
656
 
657
+ # Estimate tokens
658
+ def estimate_tokens(text):
659
+ return len(text) / 4 # Approximate token estimation
660
 
661
+ prompt_tokens = estimate_tokens(prompt)
662
+ max_tokens = 300 # Adjust as needed
663
+ total_tokens = prompt_tokens + max_tokens
664
 
665
+ # Calculate required delay
666
+ tokens_per_minute = 60000 # Adjust based on your rate limit
667
+ tokens_per_second = tokens_per_minute / 60
668
+ required_delay = total_tokens / tokens_per_second
669
+ sleep_time = max(required_delay, 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
670
 
671
+ # Acquire semaphore before making API call
672
+ api_semaphore.acquire()
 
 
673
  try:
674
+ # Call the LLM via Groq Cloud API
675
+ response = openai.ChatCompletion.create(
676
+ model='llama-3.1-70b-versatile', # Using the specified model
677
+ messages=[
678
+ {"role": "user", "content": prompt}
679
+ ],
680
+ max_tokens=int(max_tokens),
681
+ temperature=0.7,
682
+ )
683
+ finally:
684
+ # Release semaphore after API call
685
+ api_semaphore.release()
686
+
687
+ answer = response['choices'][0]['message']['content'].strip()
688
+ logger.info("Chatbot response generated")
689
+ time.sleep(sleep_time)
690
+
691
+ # Append the interaction to chat history
692
+ chat_history.append({"role": "assistant", "content": answer})
693
+ return chat_history
694
+
695
+ except openai.error.RateLimitError as e:
696
+ wait_time = int(e.headers.get("Retry-After", 5))
697
+ logger.warning(f"Rate limit reached. Waiting for {wait_time} seconds before retrying...")
698
+ time.sleep(wait_time)
699
+ return chatbot_response(user_query, chat_history) # Retry after waiting
700
+ except Exception as e:
701
+ error_message = f"⚠️ Error processing your query: {str(e)}"
702
+ logger.error(error_message, exc_info=True)
703
+ chat_history.append({"role": "assistant", "content": error_message})
704
+ return chat_history
705
+
706
+ def build_app():
707
+ """
708
+ Build and launch the Gradio app.
709
+ """
710
+ try:
711
+ logger.info("Building Gradio app")
712
+ with gr.Blocks(css="app.css") as demo:
713
+ # Initialize state
714
+ state_bookmarks = gr.State([])
715
+
716
+ # General Overview
717
+ gr.Markdown("""
718
  # πŸ“š SmartMarks - AI Browser Bookmarks Manager
719
 
720
  Welcome to **SmartMarks**, your intelligent assistant for managing browser bookmarks. SmartMarks leverages AI to help you organize, search, and interact with your bookmarks seamlessly.
 
732
  Navigate through the tabs to explore each feature in detail.
733
  """)
734
 
735
+ # Upload and Process Bookmarks Tab
736
+ with gr.Tab("Upload and Process Bookmarks"):
737
+ gr.Markdown("""
738
  ## πŸ“‚ **Upload and Process Bookmarks**
739
 
740
  ### πŸ“ **Steps to Upload and Process:**
 
751
  - Once processing is complete, your bookmarks will be displayed in an organized and visually appealing format below.
752
  """)
753
 
754
+ upload = gr.File(label="πŸ“ Upload Bookmarks HTML File", type='binary')
755
+ process_button = gr.Button("βš™οΈ Process Bookmarks")
756
+ output_text = gr.Textbox(label="βœ… Output", interactive=False)
757
+ bookmark_display = gr.HTML(label="πŸ“„ Processed Bookmarks")
758
 
759
+ process_button.click(
760
+ process_uploaded_file,
761
+ inputs=[upload, state_bookmarks],
762
+ outputs=[output_text, bookmark_display, state_bookmarks, bookmark_display]
763
+ )
764
 
765
+ # Chat with Bookmarks Tab
766
+ with gr.Tab("Chat with Bookmarks"):
767
+ gr.Markdown("""
768
  ## πŸ’¬ **Chat with Bookmarks**
769
 
770
  ### πŸ€– **How to Interact:**
 
782
  - All your queries and the corresponding AI responses are displayed in the chat history for your reference.
783
  """)
784
 
785
+ chatbot = gr.Chatbot(label="πŸ’¬ Chat with SmartMarks", type='messages')
786
+ user_input = gr.Textbox(
787
+ label="✍️ Ask about your bookmarks",
788
+ placeholder="e.g., Do I have any bookmarks about AI?"
789
+ )
790
+ chat_button = gr.Button("πŸ“¨ Send")
791
+
792
+ chat_button.click(
793
+ chatbot_response,
794
+ inputs=[user_input, chatbot],
795
+ outputs=chatbot
796
+ )
797
+
798
+ # Manage Bookmarks Tab
799
+ with gr.Tab("Manage Bookmarks"):
800
+ gr.Markdown("""
801
  ## πŸ› οΈ **Manage Bookmarks**
802
 
803
  ### πŸ—‚οΈ **Features:**
 
824
  - Click the **"πŸ”„ Refresh Bookmarks"** button to ensure the latest state is reflected in the display.
825
  """)
826
 
827
+ manage_output = gr.Textbox(label="πŸ”„ Status", interactive=False)
828
+ bookmark_selector = gr.CheckboxGroup(
829
+ label="βœ… Select Bookmarks",
830
+ choices=[]
831
+ )
832
+ new_category = gr.Dropdown(
833
+ label="πŸ†• New Category",
834
+ choices=CATEGORIES,
835
+ value="Uncategorized"
836
+ )
837
+ bookmark_display_manage = gr.HTML(label="πŸ“„ Bookmarks")
838
+
839
+ with gr.Row():
840
+ delete_button = gr.Button("πŸ—‘οΈ Delete Selected")
841
+ edit_category_button = gr.Button("✏️ Edit Category")
842
+ export_button = gr.Button("πŸ’Ύ Export")
843
+ refresh_button = gr.Button("πŸ”„ Refresh Bookmarks")
844
+
845
+ download_link = gr.File(label="πŸ“₯ Download Exported Bookmarks")
846
+
847
+ # Define button actions
848
+ delete_button.click(
849
+ delete_selected_bookmarks,
850
+ inputs=[bookmark_selector, state_bookmarks],
851
+ outputs=[manage_output, bookmark_selector, bookmark_display_manage]
852
+ )
853
+
854
+ edit_category_button.click(
855
+ edit_selected_bookmarks_category,
856
+ inputs=[bookmark_selector, new_category, state_bookmarks],
857
+ outputs=[manage_output, bookmark_selector, bookmark_display_manage, state_bookmarks]
858
+ )
859
+
860
+ export_button.click(
861
+ export_bookmarks,
862
+ outputs=download_link
863
+ )
864
+
865
+ refresh_button.click(
866
+ lambda state_bookmarks: (
867
+ [
868
+ f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})" for i, bookmark in enumerate(state_bookmarks)
869
+ ],
870
+ display_bookmarks()
871
+ ),
872
+ inputs=[state_bookmarks],
873
+ outputs=[bookmark_selector, bookmark_display_manage]
874
+ )
875
+
876
+ logger.info("Launching Gradio app")
877
+ demo.launch(debug=True)
878
+ except Exception as e:
879
+ logger.error(f"Error building the app: {e}", exc_info=True)
880
+ print(f"Error building the app: {e}")
881
 
882
+ if __name__ == "__main__":
883
+ build_app()