'''
cards += card_html
return cards
def process_uploaded_file(file):
global bookmarks, faiss_index
if file is None:
return "Please upload a bookmarks HTML file.", ''
try:
file_content = file.decode('utf-8')
except UnicodeDecodeError:
return "Error decoding the file. Please ensure it's a valid HTML file.", ''
bookmarks = parse_bookmarks(file_content)
if not bookmarks:
return "No bookmarks found in the uploaded file.", ''
# Asynchronously fetch bookmark info
asyncio.run(process_bookmarks_async(bookmarks))
# Generate summaries and assign categories
for bookmark in bookmarks:
generate_summary(bookmark)
assign_category(bookmark)
faiss_index, embeddings = vectorize_and_index(bookmarks)
message = f"Successfully processed {len(bookmarks)} bookmarks."
bookmark_html = display_bookmarks()
return message, bookmark_html
def chatbot_response(user_query):
if faiss_index is None or not bookmarks:
return "No bookmarks available. Please upload and process your bookmarks first."
# Vectorize user query
user_embedding = embedding_model.encode([user_query])
D, I = faiss_index.search(np.array(user_embedding), k=5) # Retrieve top 5 matches
# Generate response
response = ""
for idx in I[0]:
if idx < len(bookmarks):
bookmark = bookmarks[idx]
index = bookmarks.index(bookmark) + 1 # Start index at 1
response += f"{index}. Title: {bookmark['title']}\nURL: {bookmark['url']}\nCategory: {bookmark.get('category', 'Uncategorized')}\nSummary: {bookmark['summary']}\n\n"
return response.strip()
def edit_bookmark(bookmark_idx, new_title, new_url, new_category):
global faiss_index
try:
bookmark_idx = int(bookmark_idx) - 1 # Adjust index to match list (starting at 0)
if bookmark_idx < 0 or bookmark_idx >= len(bookmarks):
return "Invalid bookmark index.", display_bookmarks()
bookmarks[bookmark_idx]['title'] = new_title
bookmarks[bookmark_idx]['url'] = new_url
bookmarks[bookmark_idx]['category'] = new_category
# Re-fetch bookmark info
asyncio.run(process_bookmarks_async([bookmarks[bookmark_idx]]))
generate_summary(bookmarks[bookmark_idx])
# Rebuild the FAISS index
faiss_index, embeddings = vectorize_and_index(bookmarks)
message = "Bookmark updated successfully."
updated_html = display_bookmarks()
return message, updated_html
except Exception as e:
return f"Error: {str(e)}", display_bookmarks()
def delete_bookmarks(indices):
global faiss_index
try:
indices = sorted([int(idx) for idx in indices], reverse=True)
for idx in indices:
if 0 <= idx < len(bookmarks):
bookmarks.pop(idx)
# Rebuild the FAISS index
if bookmarks:
faiss_index, embeddings = vectorize_and_index(bookmarks)
else:
faiss_index = None
message = "Selected bookmarks deleted successfully."
updated_html = display_bookmarks()
return message, updated_html
except Exception as e:
return f"Error: {str(e)}", display_bookmarks()
def export_bookmarks():
if not bookmarks:
return None
# Create an HTML content similar to the imported bookmarks file
soup = BeautifulSoup("Bookmarks
Bookmarks
", '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)
# Encode the HTML content to base64 for download
b64 = base64.b64encode(html_content.encode()).decode()
href = f'data:text/html;base64,{b64}'
return href
def build_app():
with gr.Blocks(css="app.css") as demo:
gr.Markdown("
Bookmark Manager App
")
with gr.Tab("Upload and Process Bookmarks"):
upload = gr.File(label="Upload Bookmarks HTML File", type='binary')
process_button = gr.Button("Process Bookmarks")
output_text = gr.Textbox(label="Output")
bookmark_display = gr.HTML(label="Bookmarks")
def update_bookmark_display(file):
message, html_content = process_uploaded_file(file)
return message, html_content
process_button.click(
update_bookmark_display,
inputs=upload,
outputs=[output_text, bookmark_display]
)
with gr.Tab("Chat with Bookmarks"):
user_input = gr.Textbox(label="Ask about your bookmarks")
chat_output = gr.Textbox(label="Chatbot Response")
chat_button = gr.Button("Send")
chat_button.click(
chatbot_response,
inputs=user_input,
outputs=chat_output
)
with gr.Tab("Manage Bookmarks"):
manage_output = gr.Textbox(label="Manage Output")
bookmark_display_manage = gr.HTML(label="Bookmarks")
refresh_button = gr.Button("Refresh Bookmark List")
select_all_checkbox = gr.Checkbox(label="Select All")
selected_indices = gr.Textbox(label="Selected Indices (comma-separated)", visible=False)
with gr.Row():
index_input = gr.Number(label="Bookmark Index (Starting from 1)", precision=0)
new_title_input = gr.Textbox(label="New Title")
new_url_input = gr.Textbox(label="New URL")
new_category_input = gr.Dropdown(label="New Category", choices=CATEGORIES)
edit_button = gr.Button("Edit Bookmark")
delete_button = gr.Button("Delete Selected Bookmarks")
export_button = gr.Button("Export Bookmarks")
download_link = gr.HTML(label="Download Exported Bookmarks")
def update_manage_display():
html_content = display_bookmarks()
return html_content
refresh_button.click(
update_manage_display,
inputs=None,
outputs=bookmark_display_manage
)
edit_button.click(
edit_bookmark,
inputs=[index_input, new_title_input, new_url_input, new_category_input],
outputs=[manage_output, bookmark_display_manage]
)
delete_button.click(
delete_bookmarks,
inputs=selected_indices,
outputs=[manage_output, bookmark_display_manage]
)
def provide_download_link():
href = export_bookmarks()
if href:
return f'Download Exported Bookmarks'
else:
return "No bookmarks to export."
export_button.click(
provide_download_link,
inputs=None,
outputs=download_link
)
# Initial load of the bookmarks display
bookmark_display_manage.value = update_manage_display()
# Include JavaScript to handle checkbox selection and Select All functionality
demo.load(None, None, None, _js="""
function() {
// Handle Select All checkbox
document.querySelector('input[type="checkbox"][label="Select All"]').addEventListener('change', function() {
var checkboxes = document.querySelectorAll('.bookmark-checkbox');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = this.checked;
}
});
// Update selected indices
function updateSelectedIndices() {
var checkboxes = document.querySelectorAll('.bookmark-checkbox');
var indices = [];
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
indices.push(checkboxes[i].getAttribute('data-index'));
}
}
document.querySelector('textarea[label="Selected Indices (comma-separated)"]').value = indices.join(',');
}
document.addEventListener('change', function(e) {
if (e.target && e.target.classList.contains('bookmark-checkbox')) {
updateSelectedIndices();
}
});
}
""")
demo.launch()
if __name__ == "__main__":
build_app()