Spaces:
Sleeping
Sleeping
siddhartharya
commited on
Commit
β’
370367a
1
Parent(s):
9efe9bb
Update app.py
Browse files
app.py
CHANGED
@@ -232,24 +232,14 @@ async def fetch_url_info(session, bookmark):
|
|
232 |
content = await response.text()
|
233 |
bookmark['html_content'] = content # Store HTML content for summary generation
|
234 |
soup = BeautifulSoup(content, 'html.parser')
|
235 |
-
|
236 |
-
# Extract meta description or Open Graph description
|
237 |
-
meta_description = soup.find('meta', attrs={'name': 'description'})
|
238 |
-
og_description = soup.find('meta', attrs={'property': 'og:description'})
|
239 |
-
if og_description and og_description.get('content'):
|
240 |
-
description = og_description.get('content')
|
241 |
-
elif meta_description and meta_description.get('content'):
|
242 |
-
description = meta_description.get('content')
|
243 |
-
else:
|
244 |
-
description = ''
|
245 |
-
|
246 |
-
bookmark['description'] = description
|
247 |
logger.info(f"Fetched information for {url}")
|
248 |
except Exception as e:
|
249 |
bookmark['dead_link'] = True
|
250 |
bookmark['etag'] = 'N/A'
|
251 |
bookmark['status_code'] = 'N/A'
|
252 |
bookmark['description'] = ''
|
|
|
253 |
logger.error(f"Error fetching URL info for {url}: {e}")
|
254 |
finally:
|
255 |
fetch_cache[url] = {
|
@@ -261,8 +251,452 @@ async def fetch_url_info(session, bookmark):
|
|
261 |
}
|
262 |
return bookmark
|
263 |
|
264 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
265 |
|
266 |
-
# Starting point of the application
|
267 |
if __name__ == "__main__":
|
268 |
build_app()
|
|
|
232 |
content = await response.text()
|
233 |
bookmark['html_content'] = content # Store HTML content for summary generation
|
234 |
soup = BeautifulSoup(content, 'html.parser')
|
235 |
+
bookmark['description'] = '' # Will be set by generate_summary function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
236 |
logger.info(f"Fetched information for {url}")
|
237 |
except Exception as e:
|
238 |
bookmark['dead_link'] = True
|
239 |
bookmark['etag'] = 'N/A'
|
240 |
bookmark['status_code'] = 'N/A'
|
241 |
bookmark['description'] = ''
|
242 |
+
bookmark['html_content'] = ''
|
243 |
logger.error(f"Error fetching URL info for {url}: {e}")
|
244 |
finally:
|
245 |
fetch_cache[url] = {
|
|
|
251 |
}
|
252 |
return bookmark
|
253 |
|
254 |
+
# Asynchronous processing of bookmarks
|
255 |
+
async def process_bookmarks_async(bookmarks_list):
|
256 |
+
logger.info("Processing bookmarks asynchronously")
|
257 |
+
try:
|
258 |
+
async with aiohttp.ClientSession() as session:
|
259 |
+
tasks = []
|
260 |
+
for bookmark in bookmarks_list:
|
261 |
+
task = asyncio.ensure_future(fetch_url_info(session, bookmark))
|
262 |
+
tasks.append(task)
|
263 |
+
await asyncio.gather(*tasks)
|
264 |
+
logger.info("Completed processing bookmarks asynchronously")
|
265 |
+
except Exception as e:
|
266 |
+
logger.error(f"Error in asynchronous processing of bookmarks: {e}")
|
267 |
+
raise
|
268 |
+
|
269 |
+
# Assign category to a bookmark
|
270 |
+
def assign_category(bookmark):
|
271 |
+
if bookmark.get('dead_link'):
|
272 |
+
bookmark['category'] = 'Dead Link'
|
273 |
+
logger.info(f"Assigned category 'Dead Link' to bookmark: {bookmark.get('url')}")
|
274 |
+
return bookmark
|
275 |
+
|
276 |
+
summary = bookmark.get('summary', '').lower()
|
277 |
+
assigned_category = 'Uncategorized'
|
278 |
+
|
279 |
+
# Keywords associated with each category
|
280 |
+
category_keywords = {
|
281 |
+
"Social Media": ["social media", "networking", "friends", "connect", "posts", "profile"],
|
282 |
+
"News and Media": ["news", "journalism", "media", "headlines", "breaking news"],
|
283 |
+
"Education and Learning": ["education", "learning", "courses", "tutorial", "university", "academy", "study"],
|
284 |
+
"Entertainment": ["entertainment", "movies", "tv shows", "games", "comics", "fun"],
|
285 |
+
"Shopping and E-commerce": ["shopping", "e-commerce", "buy", "sell", "marketplace", "deals", "store"],
|
286 |
+
"Finance and Banking": ["finance", "banking", "investment", "money", "economy", "stock", "trading"],
|
287 |
+
"Technology": ["technology", "tech", "gadgets", "software", "computers", "innovation"],
|
288 |
+
"Health and Fitness": ["health", "fitness", "medical", "wellness", "exercise", "diet"],
|
289 |
+
"Travel and Tourism": ["travel", "tourism", "destinations", "hotels", "flights", "vacation"],
|
290 |
+
"Food and Recipes": ["food", "recipes", "cooking", "cuisine", "restaurant", "dining"],
|
291 |
+
"Sports": ["sports", "scores", "teams", "athletics", "matches", "leagues"],
|
292 |
+
"Arts and Culture": ["arts", "culture", "museum", "gallery", "exhibition", "artistic"],
|
293 |
+
"Government and Politics": ["government", "politics", "policy", "election", "public service"],
|
294 |
+
"Business and Economy": ["business", "corporate", "industry", "economy", "markets"],
|
295 |
+
"Science and Research": ["science", "research", "experiment", "laboratory", "study", "scientific"],
|
296 |
+
"Personal Blogs and Journals": ["blog", "journal", "personal", "diary", "thoughts", "opinions"],
|
297 |
+
"Job Search and Careers": ["jobs", "careers", "recruitment", "resume", "employment", "hiring"],
|
298 |
+
"Music and Audio": ["music", "audio", "songs", "albums", "artists", "bands"],
|
299 |
+
"Videos and Movies": ["video", "movies", "film", "clips", "trailers", "cinema"],
|
300 |
+
"Reference and Knowledge Bases": ["reference", "encyclopedia", "dictionary", "wiki", "knowledge", "information"],
|
301 |
+
}
|
302 |
+
|
303 |
+
for category, keywords in category_keywords.items():
|
304 |
+
for keyword in keywords:
|
305 |
+
if re.search(r'\b' + re.escape(keyword) + r'\b', summary):
|
306 |
+
assigned_category = category
|
307 |
+
logger.info(f"Assigned category '{assigned_category}' to bookmark: {bookmark.get('url')}")
|
308 |
+
break
|
309 |
+
if assigned_category != 'Uncategorized':
|
310 |
+
break
|
311 |
+
|
312 |
+
bookmark['category'] = assigned_category
|
313 |
+
if assigned_category == 'Uncategorized':
|
314 |
+
logger.info(f"No matching category found for bookmark: {bookmark.get('url')}")
|
315 |
+
return bookmark
|
316 |
+
|
317 |
+
# Vectorize summaries and build FAISS index
|
318 |
+
def vectorize_and_index(bookmarks_list):
|
319 |
+
logger.info("Vectorizing summaries and building FAISS index")
|
320 |
+
try:
|
321 |
+
summaries = [bookmark['summary'] for bookmark in bookmarks_list]
|
322 |
+
embeddings = embedding_model.encode(summaries)
|
323 |
+
dimension = embeddings.shape[1]
|
324 |
+
faiss_idx = faiss.IndexFlatL2(dimension)
|
325 |
+
faiss_idx.add(np.array(embeddings))
|
326 |
+
logger.info("FAISS index built successfully")
|
327 |
+
return faiss_idx, embeddings
|
328 |
+
except Exception as e:
|
329 |
+
logger.error(f"Error in vectorizing and indexing: {e}")
|
330 |
+
raise
|
331 |
+
|
332 |
+
# Generate HTML display for bookmarks
|
333 |
+
def display_bookmarks():
|
334 |
+
logger.info("Generating HTML display for bookmarks")
|
335 |
+
cards = ''
|
336 |
+
for i, bookmark in enumerate(bookmarks):
|
337 |
+
index = i + 1 # Start index at 1
|
338 |
+
status = "β Dead Link" if bookmark.get('dead_link') else "β
Active"
|
339 |
+
title = bookmark['title']
|
340 |
+
url = bookmark['url']
|
341 |
+
etag = bookmark.get('etag', 'N/A')
|
342 |
+
summary = bookmark.get('summary', '')
|
343 |
+
category = bookmark.get('category', 'Uncategorized')
|
344 |
+
|
345 |
+
# Apply inline styles using CSS variables
|
346 |
+
if bookmark.get('dead_link'):
|
347 |
+
card_style = "border: 2px solid var(--error-color);"
|
348 |
+
text_style = "color: var(--error-color);"
|
349 |
+
else:
|
350 |
+
card_style = "border: 2px solid var(--success-color);"
|
351 |
+
text_style = "color: var(--text-color);"
|
352 |
+
|
353 |
+
card_html = f'''
|
354 |
+
<div class="card" style="{card_style}; padding: 10px; margin: 10px; border-radius: 5px;">
|
355 |
+
<div class="card-content">
|
356 |
+
<h3 style="{text_style}">{index}. {title} {status}</h3>
|
357 |
+
<p style="{text_style}"><strong>Category:</strong> {category}</p>
|
358 |
+
<p style="{text_style}"><strong>URL:</strong> <a href="{url}" target="_blank" style="{text_style}">{url}</a></p>
|
359 |
+
<p style="{text_style}"><strong>ETag:</strong> {etag}</p>
|
360 |
+
<p style="{text_style}"><strong>Summary:</strong> {summary}</p>
|
361 |
+
</div>
|
362 |
+
</div>
|
363 |
+
'''
|
364 |
+
cards += card_html
|
365 |
+
logger.info("HTML display generated")
|
366 |
+
return cards
|
367 |
+
|
368 |
+
# Process the uploaded file
|
369 |
+
def process_uploaded_file(file):
|
370 |
+
global bookmarks, faiss_index
|
371 |
+
logger.info("Processing uploaded file")
|
372 |
+
if file is None:
|
373 |
+
logger.warning("No file uploaded")
|
374 |
+
return "Please upload a bookmarks HTML file.", '', gr.update(choices=[]), display_bookmarks()
|
375 |
+
try:
|
376 |
+
file_content = file.decode('utf-8')
|
377 |
+
except UnicodeDecodeError as e:
|
378 |
+
logger.error(f"Error decoding the file: {e}")
|
379 |
+
return "Error decoding the file. Please ensure it's a valid HTML file.", '', gr.update(choices=[]), display_bookmarks()
|
380 |
+
|
381 |
+
try:
|
382 |
+
bookmarks = parse_bookmarks(file_content)
|
383 |
+
except Exception as e:
|
384 |
+
logger.error(f"Error parsing bookmarks: {e}")
|
385 |
+
return "Error parsing the bookmarks HTML file.", '', gr.update(choices=[]), display_bookmarks()
|
386 |
+
|
387 |
+
if not bookmarks:
|
388 |
+
logger.warning("No bookmarks found in the uploaded file")
|
389 |
+
return "No bookmarks found in the uploaded file.", '', gr.update(choices=[]), display_bookmarks()
|
390 |
+
|
391 |
+
# Asynchronously fetch bookmark info
|
392 |
+
try:
|
393 |
+
asyncio.run(process_bookmarks_async(bookmarks))
|
394 |
+
except Exception as e:
|
395 |
+
logger.error(f"Error processing bookmarks asynchronously: {e}")
|
396 |
+
return "Error processing bookmarks.", '', gr.update(choices=[]), display_bookmarks()
|
397 |
+
|
398 |
+
# Generate summaries and assign categories
|
399 |
+
for bookmark in bookmarks:
|
400 |
+
generate_summary(bookmark)
|
401 |
+
assign_category(bookmark)
|
402 |
+
|
403 |
+
try:
|
404 |
+
faiss_index, embeddings = vectorize_and_index(bookmarks)
|
405 |
+
except Exception as e:
|
406 |
+
logger.error(f"Error building FAISS index: {e}")
|
407 |
+
return "Error building search index.", '', gr.update(choices=[]), display_bookmarks()
|
408 |
+
|
409 |
+
message = f"β
Successfully processed {len(bookmarks)} bookmarks."
|
410 |
+
logger.info(message)
|
411 |
+
bookmark_html = display_bookmarks()
|
412 |
+
|
413 |
+
# Update bookmark_selector choices
|
414 |
+
choices = [f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})" for i, bookmark in enumerate(bookmarks)]
|
415 |
+
bookmark_selector_update = gr.update(choices=choices, value=[])
|
416 |
+
|
417 |
+
# Update bookmark_display_manage
|
418 |
+
bookmark_display_manage_update = display_bookmarks()
|
419 |
+
|
420 |
+
return message, bookmark_html, bookmark_selector_update, bookmark_display_manage_update
|
421 |
+
|
422 |
+
# Delete selected bookmarks
|
423 |
+
def delete_selected_bookmarks(selected_indices):
|
424 |
+
global bookmarks, faiss_index
|
425 |
+
if not selected_indices:
|
426 |
+
return "β οΈ No bookmarks selected.", gr.update(choices=[]), display_bookmarks()
|
427 |
+
indices = [int(s.split('.')[0])-1 for s in selected_indices]
|
428 |
+
indices = sorted(indices, reverse=True)
|
429 |
+
for idx in indices:
|
430 |
+
if 0 <= idx < len(bookmarks):
|
431 |
+
logger.info(f"Deleting bookmark at index {idx + 1}")
|
432 |
+
bookmarks.pop(idx)
|
433 |
+
if bookmarks:
|
434 |
+
faiss_index, embeddings = vectorize_and_index(bookmarks)
|
435 |
+
else:
|
436 |
+
faiss_index = None
|
437 |
+
message = "ποΈ Selected bookmarks deleted successfully."
|
438 |
+
logger.info(message)
|
439 |
+
# Update bookmark_selector choices
|
440 |
+
choices = [f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})" for i, bookmark in enumerate(bookmarks)]
|
441 |
+
bookmark_selector_update = gr.update(choices=choices, value=[])
|
442 |
+
# Update bookmarks display
|
443 |
+
bookmarks_html = display_bookmarks()
|
444 |
+
return message, bookmark_selector_update, bookmarks_html
|
445 |
+
|
446 |
+
# Edit category of selected bookmarks
|
447 |
+
def edit_selected_bookmarks_category(selected_indices, new_category):
|
448 |
+
if not selected_indices:
|
449 |
+
return "β οΈ No bookmarks selected.", '', gr.update()
|
450 |
+
if not new_category:
|
451 |
+
return "β οΈ No new category selected.", '', gr.update()
|
452 |
+
indices = [int(s.split('.')[0])-1 for s in selected_indices]
|
453 |
+
for idx in indices:
|
454 |
+
if 0 <= idx < len(bookmarks):
|
455 |
+
bookmarks[idx]['category'] = new_category
|
456 |
+
logger.info(f"Updated category for bookmark {idx + 1} to {new_category}")
|
457 |
+
message = "βοΈ Category updated for selected bookmarks."
|
458 |
+
logger.info(message)
|
459 |
+
# Update bookmark_selector choices
|
460 |
+
choices = [f"{i+1}. {bookmark['title']} (Category: {bookmark['category']})" for i, bookmark in enumerate(bookmarks)]
|
461 |
+
bookmark_selector_update = gr.update(choices=choices, value=[])
|
462 |
+
# Update bookmarks display
|
463 |
+
bookmarks_html = display_bookmarks()
|
464 |
+
return message, bookmark_selector_update, bookmarks_html
|
465 |
+
|
466 |
+
# Export bookmarks to HTML
|
467 |
+
def export_bookmarks():
|
468 |
+
if not bookmarks:
|
469 |
+
logger.warning("No bookmarks to export")
|
470 |
+
return "β οΈ No bookmarks to export."
|
471 |
+
try:
|
472 |
+
logger.info("Exporting bookmarks to HTML")
|
473 |
+
# Create an HTML content similar to the imported bookmarks file
|
474 |
+
soup = BeautifulSoup("<!DOCTYPE NETSCAPE-Bookmark-file-1><Title>Bookmarks</Title><H1>Bookmarks</H1>", 'html.parser')
|
475 |
+
dl = soup.new_tag('DL')
|
476 |
+
for bookmark in bookmarks:
|
477 |
+
dt = soup.new_tag('DT')
|
478 |
+
a = soup.new_tag('A', href=bookmark['url'])
|
479 |
+
a.string = bookmark['title']
|
480 |
+
dt.append(a)
|
481 |
+
dl.append(dt)
|
482 |
+
soup.append(dl)
|
483 |
+
html_content = str(soup)
|
484 |
+
# Encode the HTML content to base64 for download
|
485 |
+
b64 = base64.b64encode(html_content.encode()).decode()
|
486 |
+
href = f'data:text/html;base64,{b64}'
|
487 |
+
logger.info("Bookmarks exported successfully")
|
488 |
+
return f'<a href="{href}" download="bookmarks.html">πΎ Download Exported Bookmarks</a>'
|
489 |
+
except Exception as e:
|
490 |
+
logger.error(f"Error exporting bookmarks: {e}")
|
491 |
+
return "β οΈ Error exporting bookmarks."
|
492 |
+
|
493 |
+
# Chatbot response using Groq Cloud API
|
494 |
+
def chatbot_response(user_query):
|
495 |
+
if not GROQ_API_KEY:
|
496 |
+
logger.warning("GROQ_API_KEY not set.")
|
497 |
+
return "β οΈ API key not set. Please set the GROQ_API_KEY environment variable in the Hugging Face Space settings."
|
498 |
+
|
499 |
+
if not bookmarks:
|
500 |
+
logger.warning("No bookmarks available for chatbot")
|
501 |
+
return "β οΈ No bookmarks available. Please upload and process your bookmarks first."
|
502 |
+
|
503 |
+
logger.info(f"Chatbot received query: {user_query}")
|
504 |
+
|
505 |
+
try:
|
506 |
+
# Limit the number of bookmarks to prevent exceeding token limits
|
507 |
+
max_bookmarks = 50 # Adjust as needed
|
508 |
+
bookmark_data = ""
|
509 |
+
for idx, bookmark in enumerate(bookmarks[:max_bookmarks]):
|
510 |
+
bookmark_data += f"{idx+1}. Title: {bookmark['title']}\nURL: {bookmark['url']}\nSummary: {bookmark['summary']}\n\n"
|
511 |
+
|
512 |
+
# Construct the prompt
|
513 |
+
prompt = f"""
|
514 |
+
You are an assistant that helps users find relevant bookmarks from their collection based on their queries.
|
515 |
+
|
516 |
+
User Query:
|
517 |
+
{user_query}
|
518 |
+
|
519 |
+
Bookmarks:
|
520 |
+
{bookmark_data}
|
521 |
+
|
522 |
+
Please identify the most relevant bookmarks that match the user's query. Provide a concise list including the index, title, URL, and a brief summary.
|
523 |
+
"""
|
524 |
+
|
525 |
+
# Call the Groq Cloud API via the OpenAI client
|
526 |
+
response = openai.ChatCompletion.create(
|
527 |
+
model='llama3-8b-8192',
|
528 |
+
messages=[
|
529 |
+
{"role": "system", "content": "You help users find relevant bookmarks based on their queries."},
|
530 |
+
{"role": "user", "content": prompt}
|
531 |
+
],
|
532 |
+
max_tokens=500,
|
533 |
+
temperature=0.7,
|
534 |
+
)
|
535 |
+
|
536 |
+
# Extract the response text
|
537 |
+
answer = response['choices'][0]['message']['content'].strip()
|
538 |
+
logger.info("Chatbot response generated using Groq Cloud API")
|
539 |
+
return answer
|
540 |
+
|
541 |
+
except Exception as e:
|
542 |
+
error_message = f"β οΈ Error processing your query: {str(e)}"
|
543 |
+
logger.error(error_message)
|
544 |
+
print(error_message) # Ensure error appears in Hugging Face Spaces logs
|
545 |
+
return error_message
|
546 |
+
|
547 |
+
# Build the Gradio app
|
548 |
+
def build_app():
|
549 |
+
try:
|
550 |
+
logger.info("Building Gradio app")
|
551 |
+
with gr.Blocks(css="app.css") as demo:
|
552 |
+
# General Overview
|
553 |
+
gr.Markdown("""
|
554 |
+
# π SmartMarks - AI Browser Bookmarks Manager
|
555 |
+
|
556 |
+
Welcome to **SmartMarks**, your intelligent assistant for managing browser bookmarks. SmartMarks leverages AI to help you organize, search, and interact with your bookmarks seamlessly. Whether you're looking to categorize your links, retrieve information quickly, or maintain an updated list, SmartMarks has you covered.
|
557 |
+
|
558 |
+
---
|
559 |
+
|
560 |
+
## π **How to Use SmartMarks**
|
561 |
+
|
562 |
+
SmartMarks is divided into three main sections:
|
563 |
+
|
564 |
+
1. **π Upload and Process Bookmarks:** Import your existing bookmarks and let SmartMarks analyze and categorize them for you.
|
565 |
+
2. **π¬ Chat with Bookmarks:** Interact with your bookmarks using natural language queries to find relevant links effortlessly.
|
566 |
+
3. **π οΈ Manage Bookmarks:** View, edit, delete, and export your bookmarks with ease.
|
567 |
+
|
568 |
+
Navigate through the tabs to explore each feature in detail.
|
569 |
+
""")
|
570 |
+
|
571 |
+
# Upload and Process Bookmarks Tab
|
572 |
+
with gr.Tab("Upload and Process Bookmarks"):
|
573 |
+
gr.Markdown("""
|
574 |
+
## π **Upload and Process Bookmarks**
|
575 |
+
|
576 |
+
### π **Steps to Upload and Process:**
|
577 |
+
|
578 |
+
1. **π½ Upload Bookmarks File:**
|
579 |
+
- Click on the **"Upload Bookmarks HTML File"** button.
|
580 |
+
- Select your browser's exported bookmarks HTML file from your device.
|
581 |
+
|
582 |
+
2. **βοΈ Process Bookmarks:**
|
583 |
+
- After uploading, click on the **"Process Bookmarks"** button.
|
584 |
+
- SmartMarks will parse your bookmarks, fetch additional information, generate summaries, and categorize each link based on predefined categories.
|
585 |
+
|
586 |
+
3. **π View Processed Bookmarks:**
|
587 |
+
- Once processing is complete, your bookmarks will be displayed in an organized and visually appealing format below.
|
588 |
+
""")
|
589 |
+
|
590 |
+
upload = gr.File(label="π Upload Bookmarks HTML File", type='binary')
|
591 |
+
process_button = gr.Button("βοΈ Process Bookmarks")
|
592 |
+
output_text = gr.Textbox(label="β
Output", interactive=False)
|
593 |
+
bookmark_display = gr.HTML(label="π Bookmarks")
|
594 |
+
|
595 |
+
# Initialize Manage Bookmarks components
|
596 |
+
bookmark_selector = gr.CheckboxGroup(label="β
Select Bookmarks", choices=[])
|
597 |
+
bookmark_display_manage = gr.HTML(label="π Manage Bookmarks Display")
|
598 |
+
|
599 |
+
process_button.click(
|
600 |
+
process_uploaded_file,
|
601 |
+
inputs=upload,
|
602 |
+
outputs=[output_text, bookmark_display, bookmark_selector, bookmark_display_manage]
|
603 |
+
)
|
604 |
+
|
605 |
+
# Chat with Bookmarks Tab
|
606 |
+
with gr.Tab("Chat with Bookmarks"):
|
607 |
+
gr.Markdown("""
|
608 |
+
## π¬ **Chat with Bookmarks**
|
609 |
+
|
610 |
+
### π€ **How to Interact:**
|
611 |
+
|
612 |
+
1. **βοΈ Enter Your Query:**
|
613 |
+
- In the **"Ask about your bookmarks"** textbox, type your question or keyword related to your bookmarks. For example, "Do I have any bookmarks about GenerativeAI?"
|
614 |
+
|
615 |
+
2. **π¨ Submit Your Query:**
|
616 |
+
- Click the **"Send"** button to submit your query.
|
617 |
+
|
618 |
+
3. **π Receive AI-Driven Responses:**
|
619 |
+
- SmartMarks will analyze your query and provide relevant bookmarks that match your request, making it easier to find specific links without manual searching.
|
620 |
+
""")
|
621 |
+
|
622 |
+
user_input = gr.Textbox(label="βοΈ Ask about your bookmarks", placeholder="e.g., Do I have any bookmarks about GenerativeAI?")
|
623 |
+
chat_output = gr.Textbox(label="π¬ Chatbot Response", interactive=False)
|
624 |
+
chat_button = gr.Button("π¨ Send")
|
625 |
+
|
626 |
+
chat_button.click(
|
627 |
+
chatbot_response,
|
628 |
+
inputs=user_input,
|
629 |
+
outputs=chat_output
|
630 |
+
)
|
631 |
+
|
632 |
+
# Manage Bookmarks Tab
|
633 |
+
with gr.Tab("Manage Bookmarks"):
|
634 |
+
gr.Markdown("""
|
635 |
+
## π οΈ **Manage Bookmarks**
|
636 |
+
|
637 |
+
### ποΈ **Features:**
|
638 |
+
|
639 |
+
1. **ποΈ View Bookmarks:**
|
640 |
+
- All your processed bookmarks are displayed here with their respective categories and summaries.
|
641 |
+
|
642 |
+
2. **β
Select Bookmarks:**
|
643 |
+
- Use the checkboxes next to each bookmark to select one, multiple, or all bookmarks you wish to manage.
|
644 |
+
|
645 |
+
3. **ποΈ Delete Selected Bookmarks:**
|
646 |
+
- After selecting the desired bookmarks, click the **"Delete Selected Bookmarks"** button to remove them from your list.
|
647 |
+
|
648 |
+
4. **βοΈ Edit Categories:**
|
649 |
+
- Select the bookmarks you want to re-categorize.
|
650 |
+
- Choose a new category from the dropdown menu labeled **"New Category"**.
|
651 |
+
- Click the **"Edit Category of Selected Bookmarks"** button to update their categories.
|
652 |
+
|
653 |
+
5. **πΎ Export Bookmarks:**
|
654 |
+
- Click the **"Export Bookmarks"** button to download your updated bookmarks as an HTML file.
|
655 |
+
- This file can be uploaded back to your browser to reflect the changes made within SmartMarks.
|
656 |
+
""")
|
657 |
+
|
658 |
+
manage_output = gr.Textbox(label="π Manage Output", interactive=False)
|
659 |
+
bookmark_display_manage = gr.HTML(label="π Manage Bookmarks Display")
|
660 |
+
bookmark_selector = gr.CheckboxGroup(label="β
Select Bookmarks", choices=[])
|
661 |
+
|
662 |
+
new_category_input = gr.Dropdown(label="π New Category", choices=CATEGORIES, value="Uncategorized")
|
663 |
+
with gr.Row():
|
664 |
+
delete_button = gr.Button("ποΈ Delete Selected Bookmarks")
|
665 |
+
edit_category_button = gr.Button("βοΈ Edit Category of Selected Bookmarks")
|
666 |
+
export_button = gr.Button("πΎ Export Bookmarks")
|
667 |
+
download_link = gr.HTML(label="π₯ Download Exported Bookmarks")
|
668 |
+
|
669 |
+
# Define button actions
|
670 |
+
delete_button.click(
|
671 |
+
delete_selected_bookmarks,
|
672 |
+
inputs=bookmark_selector,
|
673 |
+
outputs=[manage_output, bookmark_selector, bookmark_display_manage]
|
674 |
+
)
|
675 |
+
|
676 |
+
edit_category_button.click(
|
677 |
+
edit_selected_bookmarks_category,
|
678 |
+
inputs=[bookmark_selector, new_category_input],
|
679 |
+
outputs=[manage_output, bookmark_selector, bookmark_display_manage]
|
680 |
+
)
|
681 |
+
|
682 |
+
export_button.click(
|
683 |
+
export_bookmarks,
|
684 |
+
inputs=None,
|
685 |
+
outputs=download_link
|
686 |
+
)
|
687 |
+
|
688 |
+
# Initialize display after processing bookmarks
|
689 |
+
process_button.click(
|
690 |
+
process_uploaded_file,
|
691 |
+
inputs=upload,
|
692 |
+
outputs=[output_text, bookmark_display, bookmark_selector, bookmark_display_manage]
|
693 |
+
)
|
694 |
+
|
695 |
+
logger.info("Launching Gradio app")
|
696 |
+
demo.launch(debug=True)
|
697 |
+
except Exception as e:
|
698 |
+
logger.error(f"Error building the app: {e}")
|
699 |
+
print(f"Error building the app: {e}")
|
700 |
|
|
|
701 |
if __name__ == "__main__":
|
702 |
build_app()
|