File size: 31,798 Bytes
dcf746e
3223ff3
dcf746e
 
 
 
 
fe49b51
 
dcf746e
70eb2ff
dcf746e
85c9bd6
61242f1
70eb2ff
0e041b2
 
cdd7269
70eb2ff
 
 
 
c425950
 
 
61242f1
880f9ee
61242f1
cdd7269
 
61242f1
 
cdd7269
 
61242f1
 
cdd7269
 
61242f1
314bf31
c425950
 
db87ed3
18ec658
e985ab1
314bf31
 
dd78c27
 
 
 
 
 
 
 
 
 
 
 
 
0e041b2
59084a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd9d0c4
 
59084a2
 
70eb2ff
 
61242f1
70eb2ff
 
 
 
 
 
dd78c27
 
 
 
 
 
 
 
 
 
 
 
f63ecfa
dd78c27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
813f784
9efe9bb
813f784
9efe9bb
f42e018
 
3f6cb23
fb6f5e6
 
813f784
3f6cb23
fb6f5e6
 
 
 
813f784
fb6f5e6
 
3f6cb23
813f784
70eb2ff
3f6cb23
fb6f5e6
 
 
 
 
3f6cb23
9efe9bb
 
 
 
 
 
 
 
 
 
3f6cb23
f42e018
 
3f6cb23
813f784
9efe9bb
f42e018
9efe9bb
3f6cb23
fb6f5e6
813f784
 
 
 
 
 
 
3f6cb23
ad8e10f
813f784
 
 
3f6cb23
813f784
 
 
 
 
3f6cb23
813f784
f63ecfa
00cf45f
 
 
 
 
 
dd78c27
00cf45f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35f5bd8
fe49b51
35f5bd8
00cf45f
 
 
 
 
 
 
 
70eb2ff
00cf45f
 
 
 
70eb2ff
00cf45f
 
 
 
 
 
 
 
 
dd78c27
00cf45f
 
 
 
 
 
 
 
 
dd78c27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00cf45f
 
 
 
c425950
00cf45f
 
 
 
 
 
 
 
c425950
00cf45f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70eb2ff
00cf45f
ad34ca4
00cf45f
70eb2ff
00cf45f
 
 
70eb2ff
00cf45f
 
 
 
 
 
 
 
70eb2ff
00cf45f
 
 
 
 
 
 
 
 
 
 
 
 
370367a
00cf45f
 
 
 
 
f63ecfa
ab5c457
00cf45f
dd78c27
00cf45f
 
 
 
 
 
70eb2ff
00cf45f
 
 
 
 
dd78c27
 
00cf45f
dd78c27
 
 
00cf45f
dd78c27
 
 
00cf45f
dd78c27
 
 
 
 
 
00cf45f
dd78c27
00cf45f
 
dd78c27
 
 
 
 
00cf45f
dd78c27
00cf45f
dd78c27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c425950
ab5c457
00cf45f
 
 
 
 
ab5c457
00cf45f
 
 
 
70eb2ff
 
 
 
 
 
00cf45f
 
 
 
 
 
 
 
 
 
 
 
 
 
c425950
 
 
ab5c457
00cf45f
ab5c457
00cf45f
 
 
 
ab5c457
00cf45f
ab5c457
7b16cc6
70eb2ff
00cf45f
70eb2ff
 
 
7b16cc6
00cf45f
 
7b16cc6
00cf45f
 
 
7b16cc6
c425950
 
 
ab5c457
00cf45f
 
 
 
 
 
70eb2ff
00cf45f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70eb2ff
00cf45f
 
70eb2ff
00cf45f
 
 
70eb2ff
00cf45f
 
 
c425950
00cf45f
7b16cc6
00cf45f
 
 
7fcb8db
 
dd78c27
 
5b290a0
dd78c27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b290a0
 
 
dd78c27
 
 
 
 
 
 
 
5b290a0
 
00cf45f
 
 
 
c425950
00cf45f
dd78c27
00cf45f
 
 
 
 
 
 
c425950
 
 
00cf45f
 
c425950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35f5bd8
70eb2ff
00cf45f
 
c425950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70eb2ff
00cf45f
 
 
 
35f5bd8
70eb2ff
00cf45f
 
c425950
35f5bd8
c425950
 
 
ad34ca4
c425950
 
 
 
 
ad34ca4
c425950
 
ad34ca4
c425950
70eb2ff
c425950
00cf45f
 
 
 
 
 
c425950
 
 
 
 
 
70eb2ff
00cf45f
 
ad34ca4
 
c425950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70eb2ff
00cf45f
70eb2ff
ad34ca4
70eb2ff
 
 
 
 
00cf45f
 
 
 
 
 
 
 
 
 
 
c425950
00cf45f
 
 
ad34ca4
70eb2ff
 
 
 
 
 
c425950
 
 
 
 
00cf45f
c425950
 
 
 
 
00cf45f
c425950
 
 
 
8ba26a5
c425950
 
 
70eb2ff
 
c425950
 
 
 
 
 
00cf45f
 
 
 
 
 
35f5bd8
ad34ca4
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
# app.py

import gradio as gr
from bs4 import BeautifulSoup
from sentence_transformers import SentenceTransformer
import faiss
import numpy as np
import requests
import time
import re
import base64
import logging
import os
import sys
import concurrent.futures
from concurrent.futures import ThreadPoolExecutor
import threading

# Import OpenAI library
import openai

# Suppress only the single warning from urllib3 needed.
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Set up logging to output to the console
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# Create a console handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)

# Create a formatter and set it for the handler
formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s %(message)s')
console_handler.setFormatter(formatter)

# Add the handler to the logger
logger.addHandler(console_handler)

# Initialize variables and models
logger.info("Initializing variables and models")
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
faiss_index = None
bookmarks = []
fetch_cache = {}

# Groq API Rate Limits
GROQ_RPM = 30  # requests per minute
GROQ_TPM = 40000  # tokens per minute
SECONDS_PER_MINUTE = 60
MIN_TIME_BETWEEN_CALLS = SECONDS_PER_MINUTE / GROQ_RPM  # 2 seconds between calls
MAX_CONCURRENT_CALLS = 3  # Keep concurrent calls limited to prevent rate limits
TOKEN_BUFFER = 0.9  # Use 90% of token limit to be safe

# Rate limiting tools
api_lock = threading.Lock()
request_times = []  # Track request timestamps
token_usage = []    # Track token usage
LLM_SEMAPHORE = threading.Semaphore(MAX_CONCURRENT_CALLS)

# Define the categories
CATEGORIES = [
    "Social Media",
    "News and Media",
    "Education and Learning",
    "Entertainment",
    "Shopping and E-commerce",
    "Finance and Banking",
    "Technology",
    "Health and Fitness",
    "Travel and Tourism",
    "Food and Recipes",
    "Sports",
    "Arts and Culture",
    "Government and Politics",
    "Business and Economy",
    "Science and Research",
    "Personal Blogs and Journals",
    "Job Search and Careers",
    "Music and Audio",
    "Videos and Movies",
    "Reference and Knowledge Bases",
    "Dead Link",
    "Uncategorized",
]

# Set up Groq Cloud API key and base URL
GROQ_API_KEY = os.getenv('GROQ_API_KEY')

if not GROQ_API_KEY:
    logger.error("GROQ_API_KEY environment variable not set.")

openai.api_key = GROQ_API_KEY
openai.api_base = "https://api.groq.com/openai/v1"

def manage_rate_limits():
    """
    Manage both request and token rate limits.
    Returns the time to wait (if any) before making next request.
    """
    current_time = time.time()
    minute_ago = current_time - SECONDS_PER_MINUTE

    # Clean up old entries
    global request_times, token_usage
    request_times = [t for t in request_times if t > minute_ago]
    token_usage = [t for t, _ in token_usage if t > minute_ago]

    # Check request rate
    if len(request_times) >= GROQ_RPM:
        oldest_request = request_times[0]
        return max(0, SECONDS_PER_MINUTE - (current_time - oldest_request))

    # Check token rate
    total_tokens = sum(tokens for _, tokens in token_usage)
    if total_tokens >= GROQ_TPM * TOKEN_BUFFER:
        return 1.0  # Wait a second if near token limit

    return 0

def estimate_tokens(text):
    """Estimate tokens in text using GPT-3 tokenizer approximation"""
    return len(text.split()) * 1.3  # Rough estimate: 1.3 tokens per word
def extract_main_content(soup):
    """
    Extract the main content from a webpage while filtering out boilerplate content.
    """
    if not soup:
        return ""

    # Remove unwanted elements
    for element in soup(['script', 'style', 'header', 'footer', 'nav', 'aside', 'form', 'noscript']):
        element.decompose()

    # Extract text from <p> tags
    p_tags = soup.find_all('p')
    if p_tags:
        content = ' '.join([p.get_text(strip=True, separator=' ') for p in p_tags])
    else:
        # Fallback to body content
        content = soup.get_text(separator=' ', strip=True)

    # Clean up the text
    content = re.sub(r'\s+', ' ', content)

    # Truncate content to a reasonable length (e.g., 1500 words)
    words = content.split()
    if len(words) > 1500:
        content = ' '.join(words[:1500])

    return content

def get_page_metadata(soup):
    """
    Extract metadata from the webpage including title, description, and keywords.
    """
    metadata = {
        'title': '',
        'description': '',
        'keywords': ''
    }

    if not soup:
        return metadata

    # Get title
    title_tag = soup.find('title')
    if title_tag and title_tag.string:
        metadata['title'] = title_tag.string.strip()

    # Get meta description
    meta_desc = (
        soup.find('meta', attrs={'name': 'description'}) or
        soup.find('meta', attrs={'property': 'og:description'}) or
        soup.find('meta', attrs={'name': 'twitter:description'})
    )
    if meta_desc:
        metadata['description'] = meta_desc.get('content', '').strip()

    # Get meta keywords
    meta_keywords = soup.find('meta', attrs={'name': 'keywords'})
    if meta_keywords:
        metadata['keywords'] = meta_keywords.get('content', '').strip()

    # Get OG title if main title is empty
    if not metadata['title']:
        og_title = soup.find('meta', attrs={'property': 'og:title'})
        if og_title:
            metadata['title'] = og_title.get('content', '').strip()

    return metadata

def fetch_url_info(bookmark):
    """
    Fetch information about a URL.
    """
    url = bookmark['url']
    if url in fetch_cache:
        with api_lock:
            bookmark.update(fetch_cache[url])
        return

    try:
        logger.info(f"Fetching URL info for: {url}")
        headers = {
            'User-Agent': 'Mozilla/5.0',
            'Accept-Language': 'en-US,en;q=0.9',
        }
        response = requests.get(url, headers=headers, timeout=5, verify=False, allow_redirects=True)
        bookmark['etag'] = response.headers.get('ETag', 'N/A')
        bookmark['status_code'] = response.status_code

        content = response.text
        logger.info(f"Fetched content length for {url}: {len(content)} characters")

        if response.status_code >= 500:
            bookmark['dead_link'] = True
            bookmark['description'] = ''
            bookmark['html_content'] = ''
            logger.warning(f"Dead link detected: {url} with status {response.status_code}")
        else:
            bookmark['dead_link'] = False
            bookmark['html_content'] = content
            bookmark['description'] = ''
            logger.info(f"Fetched information for {url}")

    except requests.exceptions.Timeout:
        bookmark['dead_link'] = False
        bookmark['etag'] = 'N/A'
        bookmark['status_code'] = 'Timeout'
        bookmark['description'] = ''
        bookmark['html_content'] = ''
        bookmark['slow_link'] = True
        logger.warning(f"Timeout while fetching {url}. Marking as 'Slow'.")
    except Exception as e:
        bookmark['dead_link'] = True
        bookmark['etag'] = 'N/A'
        bookmark['status_code'] = 'Error'
        bookmark['description'] = ''
        bookmark['html_content'] = ''
        logger.error(f"Error fetching URL info for {url}: {e}", exc_info=True)
    finally:
        with api_lock:
            fetch_cache[url] = {
                'etag': bookmark.get('etag'),
                'status_code': bookmark.get('status_code'),
                'dead_link': bookmark.get('dead_link'),
                'description': bookmark.get('description'),
                'html_content': bookmark.get('html_content', ''),
                'slow_link': bookmark.get('slow_link', False),
            }

def process_bookmarks_batch(bookmarks_batch):
    """Process a batch of bookmarks with controlled rate limiting"""
    for bookmark in bookmarks_batch:
        with LLM_SEMAPHORE:
            while True:
                with api_lock:
                    wait_time = manage_rate_limits()
                    if wait_time <= 0:
                        break
                    logger.info(f"Rate limiting: Waiting for {wait_time:.2f} seconds...")
                    time.sleep(wait_time)

                try:
                    html_content = bookmark.get('html_content', '')
                    soup = BeautifulSoup(html_content, 'html.parser')
                    metadata = get_page_metadata(soup)
                    main_content = extract_main_content(soup)

                    # Prepare shortened prompt to reduce tokens
                    content = f"Title: {metadata['title']}\nURL: {bookmark['url']}"
                    if len(main_content) > 1000:  # Limit content length
                        main_content = main_content[:1000] + "..."
                    
                    prompt = f"""Analyze this webpage:
{content}
Content: {main_content}
Provide in format:
Summary: [2 sentences max]
Category: [{', '.join(CATEGORIES)}]"""

                    # Estimate tokens
                    input_tokens = estimate_tokens(prompt)
                    max_tokens = 150
                    total_tokens = input_tokens + max_tokens

                    # Make API call
                    response = openai.ChatCompletion.create(
                        model='llama-3.1-70b-versatile',
                        messages=[{"role": "user", "content": prompt}],
                        max_tokens=max_tokens,
                        temperature=0.5,
                    )

                    # Track rate limits
                    with api_lock:
                        current_time = time.time()
                        request_times.append(current_time)
                        token_usage.append((current_time, total_tokens))

                    content = response['choices'][0]['message']['content'].strip()
                    
                    # Process response
                    summary_match = re.search(r"Summary:\s*(.*?)(?:\n|$)", content)
                    category_match = re.search(r"Category:\s*(.*?)(?:\n|$)", content)

                    bookmark['summary'] = summary_match.group(1).strip() if summary_match else 'No summary available.'
                    
                    if category_match:
                        category = category_match.group(1).strip().strip('"')
                        bookmark['category'] = category if category in CATEGORIES else 'Uncategorized'
                    else:
                        bookmark['category'] = 'Uncategorized'

                    # Quick category validation
                    if 'social media' in bookmark['url'].lower() or 'twitter' in bookmark['url'].lower() or 'x.com' in bookmark['url'].lower():
                        bookmark['category'] = 'Social Media'
                    elif 'wikipedia' in bookmark['url'].lower():
                        bookmark['category'] = 'Reference and Knowledge Bases'

                    logger.info(f"Successfully processed bookmark: {bookmark['url']}")
                    break

                except openai.error.RateLimitError as e:
                    wait_time = int(e.headers.get('Retry-After', 5))
                    logger.warning(f"Rate limit hit, waiting {wait_time} seconds...")
                    time.sleep(wait_time)
                except Exception as e:
                    logger.error(f"Error processing bookmark: {e}")
                    bookmark['summary'] = 'Processing failed.'
                    bookmark['category'] = 'Uncategorized'
                    break
def vectorize_and_index(bookmarks_list):
    """
    Create vector embeddings for bookmarks and build FAISS index with ID mapping.
    """
    global faiss_index
    logger.info("Vectorizing summaries and building FAISS index")
    try:
        summaries = [bookmark['summary'] for bookmark in bookmarks_list]
        embeddings = embedding_model.encode(summaries)
        dimension = embeddings.shape[1]
        index = faiss.IndexIDMap(faiss.IndexFlatL2(dimension))
        ids = np.array([bookmark['id'] for bookmark in bookmarks_list], dtype=np.int64)
        index.add_with_ids(np.array(embeddings).astype('float32'), ids)
        faiss_index = index
        logger.info("FAISS index built successfully with IDs")
        return index
    except Exception as e:
        logger.error(f"Error in vectorizing and indexing: {e}", exc_info=True)
        raise

def display_bookmarks():
    """
    Generate HTML display for bookmarks.
    """
    logger.info("Generating HTML display for bookmarks")
    cards = ''
    for i, bookmark in enumerate(bookmarks):
        index = i + 1
        if bookmark.get('dead_link'):
            status = "❌ Dead Link"
            card_style = "border: 2px solid red;"
            text_style = "color: white;"
        elif bookmark.get('slow_link'):
            status = "⏳ Slow Response"
            card_style = "border: 2px solid orange;"
            text_style = "color: white;"
        else:
            status = "βœ… Active"
            card_style = "border: 2px solid green;"
            text_style = "color: white;"

        title = bookmark['title']
        url = bookmark['url']
        etag = bookmark.get('etag', 'N/A')
        summary = bookmark.get('summary', '')
        category = bookmark.get('category', 'Uncategorized')

        # Escape HTML content to prevent XSS attacks
        from html import escape
        title = escape(title)
        url = escape(url)
        summary = escape(summary)
        category = escape(category)

        card_html = f'''
        <div class="card" style="{card_style} padding: 10px; margin: 10px; border-radius: 5px; background-color: #1e1e1e;">
            <div class="card-content">
                <h3 style="{text_style}">{index}. {title} {status}</h3>
                <p style="{text_style}"><strong>Category:</strong> {category}</p>
                <p style="{text_style}"><strong>URL:</strong> <a href="{url}" target="_blank" style="{text_style}">{url}</a></p>
                <p style="{text_style}"><strong>ETag:</strong> {etag}</p>
                <p style="{text_style}"><strong>Summary:</strong> {summary}</p>
            </div>
        </div>
        '''
        cards += card_html
    logger.info("HTML display generated")
    return cards

def process_uploaded_file(file, state_bookmarks):
    """
    Process uploaded file with optimized batch processing
    """
    global bookmarks, faiss_index
    logger.info("Processing uploaded file")

    if file is None:
        logger.warning("No file uploaded")
        return "Please upload a bookmarks HTML file.", '', state_bookmarks, display_bookmarks(), gr.update(choices=[])

    try:
        file_content = file.decode('utf-8')
        bookmarks = parse_bookmarks(file_content)

        if not bookmarks:
            return "No bookmarks found in the file.", '', state_bookmarks, display_bookmarks(), gr.update(choices=[])

        # Assign IDs
        for idx, bookmark in enumerate(bookmarks):
            bookmark['id'] = idx

        # First fetch all URLs concurrently
        with ThreadPoolExecutor(max_workers=10) as executor:
            executor.map(fetch_url_info, bookmarks)

        # Process bookmarks in parallel with controlled concurrency
        batch_size = min(MAX_CONCURRENT_CALLS, len(bookmarks))
        batches = [bookmarks[i:i + batch_size] for i in range(0, len(bookmarks), batch_size)]
        
        with ThreadPoolExecutor(max_workers=MAX_CONCURRENT_CALLS) as executor:
            executor.map(process_bookmarks_batch, batches)

        # Build FAISS index
        faiss_index = vectorize_and_index(bookmarks)

        # Update display and state
        bookmark_html = display_bookmarks()
        choices = [f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})"
                  for i, bookmark in enumerate(bookmarks)]
        state_bookmarks = bookmarks.copy()

        return "βœ… Processing complete!", bookmark_html, state_bookmarks, bookmark_html, gr.update(choices=choices)

    except Exception as e:
        logger.error(f"Error processing file: {e}")
        return f"Error processing file: {str(e)}", '', state_bookmarks, display_bookmarks(), gr.update(choices=[])

def parse_bookmarks(file_content):
    """
    Parse bookmarks from HTML file.
    """
    logger.info("Parsing bookmarks")
    try:
        soup = BeautifulSoup(file_content, 'html.parser')
        extracted_bookmarks = []
        for link in soup.find_all('a'):
            url = link.get('href')
            title = link.text.strip()
            if url and title:
                if url.startswith('http://') or url.startswith('https://'):
                    extracted_bookmarks.append({'url': url, 'title': title})
                else:
                    logger.info(f"Skipping non-http/https URL: {url}")
        logger.info(f"Extracted {len(extracted_bookmarks)} bookmarks")
        return extracted_bookmarks
    except Exception as e:
        logger.error("Error parsing bookmarks: %s", e, exc_info=True)
        raise

def delete_selected_bookmarks(selected_indices, state_bookmarks):
    """
    Delete selected bookmarks and remove their vectors from the FAISS index.
    """
    global bookmarks, faiss_index
    if not selected_indices:
        return "⚠️ No bookmarks selected.", gr.update(choices=[]), display_bookmarks()

    ids_to_delete = []
    indices_to_delete = []
    for s in selected_indices:
        idx = int(s.split('.')[0]) - 1
        if 0 <= idx < len(bookmarks):
            bookmark_id = bookmarks[idx]['id']
            ids_to_delete.append(bookmark_id)
            indices_to_delete.append(idx)
            logger.info(f"Deleting bookmark at index {idx + 1}")

    # Remove vectors from FAISS index
    if faiss_index is not None and ids_to_delete:
        faiss_index.remove_ids(np.array(ids_to_delete, dtype=np.int64))

    # Remove bookmarks from the list (reverse order to avoid index shifting)
    for idx in sorted(indices_to_delete, reverse=True):
        bookmarks.pop(idx)

    message = "πŸ—‘οΈ Selected bookmarks deleted successfully."
    logger.info(message)
    choices = [f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})"
               for i, bookmark in enumerate(bookmarks)]

    # Update state
    state_bookmarks = bookmarks.copy()

    return message, gr.update(choices=choices), display_bookmarks()

def edit_selected_bookmarks_category(selected_indices, new_category, state_bookmarks):
    """
    Edit category of selected bookmarks.
    """
    if not selected_indices:
        return "⚠️ No bookmarks selected.", gr.update(choices=[]), display_bookmarks(), state_bookmarks
    if not new_category:
        return "⚠️ No new category selected.", gr.update(choices=[]), display_bookmarks(), state_bookmarks

    indices = [int(s.split('.')[0])-1 for s in selected_indices]
    for idx in indices:
        if 0 <= idx < len(bookmarks):
            bookmarks[idx]['category'] = new_category
            logger.info(f"Updated category for bookmark {idx + 1} to {new_category}")

    message = "✏️ Category updated for selected bookmarks."
    logger.info(message)

    # Update choices and display
    choices = [f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})"
               for i, bookmark in enumerate(bookmarks)]

    # Update state
    state_bookmarks = bookmarks.copy()

    return message, gr.update(choices=choices), display_bookmarks(), state_bookmarks
def export_bookmarks():
    """
    Export bookmarks to an HTML file.
    """
    if not bookmarks:
        logger.warning("No bookmarks to export")
        return None

    try:
        logger.info("Exporting bookmarks to HTML")
        soup = BeautifulSoup("<!DOCTYPE NETSCAPE-Bookmark-file-1><Title>Bookmarks</Title><H1>Bookmarks</H1>", 'html.parser')
        dl = soup.new_tag('DL')
        for bookmark in bookmarks:
            dt = soup.new_tag('DT')
            a = soup.new_tag('A', href=bookmark['url'])
            a.string = bookmark['title']
            dt.append(a)
            dl.append(dt)
        soup.append(dl)
        html_content = str(soup)
        output_file = "exported_bookmarks.html"
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(html_content)
        logger.info("Bookmarks exported successfully")
        return output_file
    except Exception as e:
        logger.error(f"Error exporting bookmarks: {e}", exc_info=True)
        return None

def chatbot_response(user_query, chat_history):
    """
    Generate chatbot response using the FAISS index and embeddings.
    """
    if not bookmarks or faiss_index is None:
        logger.warning("No bookmarks available for chatbot")
        chat_history.append({"role": "assistant", "content": "⚠️ No bookmarks available. Please upload and process your bookmarks first."})
        return chat_history

    logger.info(f"Chatbot received query: {user_query}")

    try:
        chat_history.append({"role": "user", "content": user_query})

        with LLM_SEMAPHORE:
            while True:
                with api_lock:
                    wait_time = manage_rate_limits()
                    if wait_time <= 0:
                        break
                    logger.info(f"Rate limiting: Waiting for {wait_time:.2f} seconds...")
                    time.sleep(wait_time)

                try:
                    # Search for relevant bookmarks
                    query_vector = embedding_model.encode([user_query]).astype('float32')
                    k = 5
                    distances, ids = faiss_index.search(query_vector, k)
                    ids = ids.flatten()

                    id_to_bookmark = {bookmark['id']: bookmark for bookmark in bookmarks}
                    matching_bookmarks = [id_to_bookmark.get(id) for id in ids if id in id_to_bookmark]

                    if not matching_bookmarks:
                        answer = "No relevant bookmarks found for your query."
                        chat_history.append({"role": "assistant", "content": answer})
                        return chat_history

                    # Prepare concise prompt
                    bookmarks_info = "\n".join([
                        f"Title: {bookmark['title']}\nURL: {bookmark['url']}\nSummary: {bookmark['summary']}"
                        for bookmark in matching_bookmarks
                    ])

                    prompt = f"""User Query: "{user_query}"
Found Bookmarks:
{bookmarks_info}
Provide a helpful, concise response."""

                    # Estimate tokens and make API call
                    input_tokens = estimate_tokens(prompt)
                    max_tokens = 300
                    total_tokens = input_tokens + max_tokens

                    response = openai.ChatCompletion.create(
                        model='llama-3.1-70b-versatile',
                        messages=[{"role": "user", "content": prompt}],
                        max_tokens=max_tokens,
                        temperature=0.7,
                    )

                    # Track rate limits
                    with api_lock:
                        current_time = time.time()
                        request_times.append(current_time)
                        token_usage.append((current_time, total_tokens))

                    answer = response['choices'][0]['message']['content'].strip()
                    logger.info("Chatbot response generated")
                    
                    chat_history.append({"role": "assistant", "content": answer})
                    return chat_history

                except openai.error.RateLimitError as e:
                    wait_time = int(e.headers.get('Retry-After', 5))
                    logger.warning(f"Rate limit hit, waiting {wait_time} seconds...")
                    time.sleep(wait_time)
                    continue
                except Exception as e:
                    error_message = f"⚠️ Error processing your query: {str(e)}"
                    logger.error(error_message, exc_info=True)
                    chat_history.append({"role": "assistant", "content": error_message})
                    return chat_history

    except Exception as e:
        error_message = f"⚠️ Error processing your query: {str(e)}"
        logger.error(error_message, exc_info=True)
        chat_history.append({"role": "assistant", "content": error_message})
        return chat_history

def build_app():
    """
    Build and launch the Gradio app.
    """
    try:
        logger.info("Building Gradio app")
        with gr.Blocks(css="app.css") as demo:
            # Initialize state
            state_bookmarks = gr.State([])

            # General Overview
            gr.Markdown("""
# πŸ“š SmartMarks - AI Browser Bookmarks Manager

Welcome to **SmartMarks**, your intelligent assistant for managing browser bookmarks. SmartMarks leverages AI to help you organize, search, and interact with your bookmarks seamlessly.

---

## πŸš€ **How to Use SmartMarks**

SmartMarks is divided into three main sections:

1. **πŸ“‚ Upload and Process Bookmarks:** Import your existing bookmarks and let SmartMarks analyze and categorize them for you.
2. **πŸ’¬ Chat with Bookmarks:** Interact with your bookmarks using natural language queries to find relevant links effortlessly.
3. **πŸ› οΈ Manage Bookmarks:** View, edit, delete, and export your bookmarks with ease.

Navigate through the tabs to explore each feature in detail.
""")

            # Upload and Process Bookmarks Tab
            with gr.Tab("Upload and Process Bookmarks"):
                gr.Markdown("""
## πŸ“‚ **Upload and Process Bookmarks**

### πŸ“ **Steps to Upload and Process:**

1. **Upload Bookmarks File:**
   - Click on the **"πŸ“ Upload Bookmarks HTML File"** button.
   - Select your browser's exported bookmarks HTML file from your device.

2. **Process Bookmarks:**
   - After uploading, click on the **"βš™οΈ Process Bookmarks"** button.
   - SmartMarks will parse your bookmarks, fetch additional information, generate summaries, and categorize each link based on predefined categories.

3. **View Processed Bookmarks:**
   - Once processing is complete, your bookmarks will be displayed in an organized and visually appealing format below.
""")

                upload = gr.File(label="πŸ“ Upload Bookmarks HTML File", type='binary')
                process_button = gr.Button("βš™οΈ Process Bookmarks")
                output_text = gr.Textbox(label="βœ… Output", interactive=False)
                bookmark_display = gr.HTML(label="πŸ“„ Processed Bookmarks")

            # Chat with Bookmarks Tab
            with gr.Tab("Chat with Bookmarks"):
                gr.Markdown("""
## πŸ’¬ **Chat with Bookmarks**

### πŸ€– **How to Interact:**

1. **Enter Your Query:**
   - In the **"✍️ Ask about your bookmarks"** textbox, type your question or keyword related to your bookmarks.

2. **Submit Your Query:**
   - Click the **"πŸ“¨ Send"** button to submit your query.

3. **Receive AI-Driven Responses:**
   - SmartMarks will analyze your query and provide relevant bookmarks that match your request.

4. **View Chat History:**
   - All your queries and the corresponding AI responses are displayed in the chat history.
""")

                chatbot = gr.Chatbot(label="πŸ’¬ Chat with SmartMarks", type='messages')
                user_input = gr.Textbox(
                    label="✍️ Ask about your bookmarks",
                    placeholder="e.g., Do I have any bookmarks about AI?"
                )
                chat_button = gr.Button("πŸ“¨ Send")

                chat_button.click(
                    chatbot_response,
                    inputs=[user_input, chatbot],
                    outputs=chatbot
                )

            # Manage Bookmarks Tab
            with gr.Tab("Manage Bookmarks"):
                gr.Markdown("""
## πŸ› οΈ **Manage Bookmarks**

### πŸ—‚οΈ **Features:**

1. **View Bookmarks:**
   - All your processed bookmarks are displayed here with their respective categories and summaries.

2. **Select Bookmarks:**
   - Use the checkboxes next to each bookmark to select one, multiple, or all bookmarks you wish to manage.

3. **Delete Selected Bookmarks:**
   - After selecting the desired bookmarks, click the **"πŸ—‘οΈ Delete Selected"** button to remove them from your list.

4. **Edit Categories:**
   - Select the bookmarks you want to re-categorize.
   - Choose a new category from the dropdown menu labeled **"πŸ†• New Category"**.
   - Click the **"✏️ Edit Category"** button to update their categories.

5. **Export Bookmarks:**
   - Click the **"πŸ’Ύ Export"** button to download your updated bookmarks as an HTML file.

6. **Refresh Bookmarks:**
   - Click the **"πŸ”„ Refresh Bookmarks"** button to ensure the latest state is reflected in the display.
""")

                manage_output = gr.Textbox(label="πŸ”„ Status", interactive=False)
                
                # Move bookmark_selector here
                bookmark_selector = gr.CheckboxGroup(
                    label="βœ… Select Bookmarks",
                    choices=[]
                )
                
                new_category = gr.Dropdown(
                    label="πŸ†• New Category",
                    choices=CATEGORIES,
                    value="Uncategorized"
                )
                bookmark_display_manage = gr.HTML(label="πŸ“„ Bookmarks")

                with gr.Row():
                    delete_button = gr.Button("πŸ—‘οΈ Delete Selected")
                    edit_category_button = gr.Button("✏️ Edit Category")
                    export_button = gr.Button("πŸ’Ύ Export")
                    refresh_button = gr.Button("πŸ”„ Refresh Bookmarks")

                download_link = gr.File(label="πŸ“₯ Download Exported Bookmarks")

                # Connect all the button actions
                process_button.click(
                    process_uploaded_file,
                    inputs=[upload, state_bookmarks],
                    outputs=[output_text, bookmark_display, state_bookmarks, bookmark_display, bookmark_selector]
                )

                delete_button.click(
                    delete_selected_bookmarks,
                    inputs=[bookmark_selector, state_bookmarks],
                    outputs=[manage_output, bookmark_selector, bookmark_display_manage]
                )

                edit_category_button.click(
                    edit_selected_bookmarks_category,
                    inputs=[bookmark_selector, new_category, state_bookmarks],
                    outputs=[manage_output, bookmark_selector, bookmark_display_manage, state_bookmarks]
                )

                export_button.click(
                    export_bookmarks,
                    outputs=download_link
                )

                refresh_button.click(
                    lambda state_bookmarks: (
                        [
                            f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})" 
                            for i, bookmark in enumerate(state_bookmarks)
                        ],
                        display_bookmarks()
                    ),
                    inputs=[state_bookmarks],
                    outputs=[bookmark_selector, bookmark_display_manage]
                )

        logger.info("Launching Gradio app")
        demo.launch(debug=True)
    except Exception as e:
        logger.error(f"Error building the app: {e}", exc_info=True)
        print(f"Error building the app: {e}")

if __name__ == "__main__":
    build_app()