Spaces:
Sleeping
Sleeping
siddhartharya
commited on
Commit
β’
00cf45f
1
Parent(s):
35f5bd8
Update app.py
Browse files
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 #
|
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 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
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.
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
454 |
</div>
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
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 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
476 |
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
|
483 |
-
|
484 |
-
|
485 |
-
return "No bookmarks found in the uploaded file.", '', gr.update(choices=[]), display_bookmarks()
|
486 |
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
|
491 |
-
|
492 |
-
|
493 |
-
with ThreadPoolExecutor(max_workers=3) as executor: # Adjusted max_workers to 3
|
494 |
-
executor.map(fetch_url_info, bookmarks)
|
495 |
|
496 |
-
|
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 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
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 |
-
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
598 |
-
|
599 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
614 |
|
615 |
-
|
616 |
-
|
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 |
-
|
649 |
-
|
650 |
-
|
651 |
|
652 |
-
|
653 |
-
|
654 |
-
|
655 |
|
656 |
-
|
657 |
-
|
658 |
-
|
659 |
-
|
660 |
-
|
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 |
-
|
698 |
-
|
699 |
-
Build and launch the Gradio app.
|
700 |
-
"""
|
701 |
try:
|
702 |
-
|
703 |
-
|
704 |
-
#
|
705 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
724 |
-
|
725 |
-
|
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 |
-
|
743 |
-
|
744 |
-
|
745 |
-
|
746 |
|
747 |
-
|
748 |
-
|
749 |
-
|
750 |
-
|
751 |
-
|
752 |
|
753 |
-
|
754 |
-
|
755 |
-
|
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 |
-
|
774 |
-
|
775 |
-
|
776 |
-
|
777 |
-
|
778 |
-
|
779 |
-
|
780 |
-
|
781 |
-
|
782 |
-
|
783 |
-
|
784 |
-
|
785 |
-
|
786 |
-
|
787 |
-
|
788 |
-
|
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 |
-
|
816 |
-
|
817 |
-
|
818 |
-
|
819 |
-
|
820 |
-
|
821 |
-
|
822 |
-
|
823 |
-
|
824 |
-
|
825 |
-
|
826 |
-
|
827 |
-
|
828 |
-
|
829 |
-
|
830 |
-
|
831 |
-
|
832 |
-
|
833 |
-
|
834 |
-
|
835 |
-
|
836 |
-
|
837 |
-
|
838 |
-
|
839 |
-
|
840 |
-
|
841 |
-
|
842 |
-
|
843 |
-
|
844 |
-
|
845 |
-
|
846 |
-
|
847 |
-
|
848 |
-
|
849 |
-
|
850 |
-
|
851 |
-
|
852 |
-
|
853 |
-
|
854 |
-
|
855 |
-
|
856 |
-
|
857 |
-
|
858 |
-
|
859 |
-
|
860 |
-
|
861 |
-
|
862 |
-
|
863 |
-
|
864 |
-
|
865 |
-
|
866 |
-
|
867 |
-
|
868 |
-
|
869 |
|
870 |
-
|
871 |
-
|
|
|
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()
|