siddhartharya commited on
Commit
1e99b99
1 Parent(s): fda2e61

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -107
app.py CHANGED
@@ -1,4 +1,5 @@
1
  # app.py
 
2
  import gradio as gr
3
  from bs4 import BeautifulSoup
4
  import requests
@@ -12,8 +13,8 @@ import base64
12
  import logging
13
  import os
14
 
15
- # Import Hugging Face transformers
16
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
17
 
18
  # Set up logging
19
  logging.basicConfig(filename='app.log', level=logging.INFO,
@@ -53,10 +54,15 @@ CATEGORIES = [
53
  "Uncategorized",
54
  ]
55
 
56
- # Load FLAN-T5 model and tokenizer
57
- logger.info("Loading FLAN-T5 model and tokenizer")
58
- tokenizer = AutoTokenizer.from_pretrained('google/flan-t5-small')
59
- model = AutoModelForSeq2SeqLM.from_pretrained('google/flan-t5-small')
 
 
 
 
 
60
 
61
  # Function to parse bookmarks from HTML
62
  def parse_bookmarks(file_content):
@@ -299,7 +305,7 @@ def process_uploaded_file(file):
299
  bookmark_html = display_bookmarks()
300
  return message, bookmark_html
301
 
302
- # Chatbot response using Hugging Face model
303
  def chatbot_response(user_query):
304
  if not bookmarks:
305
  logger.warning("No bookmarks available for chatbot")
@@ -307,24 +313,42 @@ def chatbot_response(user_query):
307
 
308
  logger.info(f"Chatbot received query: {user_query}")
309
 
310
- # Prepare the context
311
  try:
312
- # Combine bookmark summaries into context
313
  max_bookmarks = 50 # Adjust as needed
314
- bookmark_context = ""
315
  for idx, bookmark in enumerate(bookmarks[:max_bookmarks]):
316
- bookmark_context += f"{idx+1}. Title: {bookmark['title']}\nSummary: {bookmark['summary']}\n\n"
317
 
318
  # Construct the prompt
319
- prompt = f"Based on the following bookmarks, answer the user's query.\n\nUser query: {user_query}\n\nBookmarks:\n{bookmark_context}"
320
-
321
- # Generate response
322
- inputs = tokenizer(prompt, return_tensors='pt', max_length=512, truncation=True)
323
- outputs = model.generate(**inputs, max_length=512)
324
- generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
325
-
326
- logger.info("Chatbot response generated using FLAN-T5 model")
327
- return generated_text.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
 
329
  except Exception as e:
330
  logger.error(f"Error in chatbot response generation: {e}")
@@ -408,93 +432,97 @@ def export_bookmarks():
408
 
409
  # Build the Gradio app
410
  def build_app():
411
- logger.info("Building Gradio app")
412
- with gr.Blocks(css="app.css") as demo:
413
- gr.Markdown("<h1>Bookmark Manager App</h1>")
414
-
415
- with gr.Tab("Upload and Process Bookmarks"):
416
- upload = gr.File(label="Upload Bookmarks HTML File", type='binary')
417
- process_button = gr.Button("Process Bookmarks")
418
- output_text = gr.Textbox(label="Output")
419
- bookmark_display = gr.HTML(label="Bookmarks")
420
-
421
- def update_bookmark_display(file):
422
- return process_uploaded_file(file)
423
-
424
- process_button.click(
425
- update_bookmark_display,
426
- inputs=upload,
427
- outputs=[output_text, bookmark_display]
428
- )
429
-
430
- with gr.Tab("Chat with Bookmarks"):
431
- user_input = gr.Textbox(label="Ask about your bookmarks")
432
- chat_output = gr.Textbox(label="Chatbot Response")
433
- chat_button = gr.Button("Send")
434
-
435
- chat_button.click(
436
- chatbot_response,
437
- inputs=user_input,
438
- outputs=chat_output
439
- )
440
-
441
- with gr.Tab("Manage Bookmarks"):
442
- manage_output = gr.Textbox(label="Manage Output")
443
- bookmark_display_manage = gr.HTML(label="Bookmarks")
444
- refresh_button = gr.Button("Refresh Bookmark List")
445
-
446
- indices_input = gr.Textbox(label="Bookmark Indices to Delete (comma-separated)")
447
- delete_button = gr.Button("Delete Selected Bookmarks")
448
- export_button = gr.Button("Export Bookmarks")
449
- download_link = gr.HTML(label="Download Exported Bookmarks")
450
-
451
- with gr.Row():
452
- index_input = gr.Number(label="Bookmark Index (Starting from 1)", precision=0)
453
- new_title_input = gr.Textbox(label="New Title")
454
- new_url_input = gr.Textbox(label="New URL")
455
- new_category_input = gr.Dropdown(label="New Category", choices=CATEGORIES)
456
-
457
- edit_button = gr.Button("Edit Bookmark")
458
-
459
- def update_manage_display():
460
- return display_bookmarks()
461
-
462
- refresh_button.click(
463
- update_manage_display,
464
- inputs=None,
465
- outputs=bookmark_display_manage
466
- )
467
-
468
- edit_button.click(
469
- edit_bookmark,
470
- inputs=[index_input, new_title_input, new_url_input, new_category_input],
471
- outputs=[manage_output, bookmark_display_manage]
472
- )
473
-
474
- delete_button.click(
475
- delete_bookmarks,
476
- inputs=indices_input,
477
- outputs=[manage_output, bookmark_display_manage]
478
- )
479
-
480
- def provide_download_link():
481
- href = export_bookmarks()
482
- if href:
483
- return f'<a href="{href}" download="bookmarks.html">Download Exported Bookmarks</a>'
484
- else:
485
- return "No bookmarks to export."
486
-
487
- export_button.click(
488
- provide_download_link,
489
- inputs=None,
490
- outputs=download_link
491
- )
492
-
493
- # Initial load of the bookmarks display
494
- bookmark_display_manage.value = update_manage_display()
495
-
496
- logger.info("Launching Gradio app")
497
- demo.launch()
 
 
 
 
498
 
499
  if __name__ == "__main__":
500
  build_app()
 
1
  # app.py
2
+
3
  import gradio as gr
4
  from bs4 import BeautifulSoup
5
  import requests
 
13
  import logging
14
  import os
15
 
16
+ # Import OpenAI library
17
+ import openai
18
 
19
  # Set up logging
20
  logging.basicConfig(filename='app.log', level=logging.INFO,
 
54
  "Uncategorized",
55
  ]
56
 
57
+ # Set up Groq Cloud API key and base URL
58
+ GROQ_API_KEY = os.getenv('GROQ_API_KEY')
59
+ if not GROQ_API_KEY:
60
+ logger.error("GROQ_API_KEY environment variable not set.")
61
+ raise ValueError("Please set the GROQ_API_KEY environment variable.")
62
+
63
+ # Set OpenAI API key and base URL to use Groq Cloud API
64
+ openai.api_key = GROQ_API_KEY
65
+ openai.api_base = "https://api.groq.com/openai/v1"
66
 
67
  # Function to parse bookmarks from HTML
68
  def parse_bookmarks(file_content):
 
305
  bookmark_html = display_bookmarks()
306
  return message, bookmark_html
307
 
308
+ # Chatbot response using Groq Cloud API
309
  def chatbot_response(user_query):
310
  if not bookmarks:
311
  logger.warning("No bookmarks available for chatbot")
 
313
 
314
  logger.info(f"Chatbot received query: {user_query}")
315
 
316
+ # Prepare the prompt for the LLM
317
  try:
318
+ # Limit the number of bookmarks to prevent exceeding token limits
319
  max_bookmarks = 50 # Adjust as needed
320
+ bookmark_data = ""
321
  for idx, bookmark in enumerate(bookmarks[:max_bookmarks]):
322
+ bookmark_data += f"{idx+1}. Title: {bookmark['title']}\nURL: {bookmark['url']}\nSummary: {bookmark['summary']}\n\n"
323
 
324
  # Construct the prompt
325
+ prompt = f"""
326
+ You are an assistant that helps users find relevant bookmarks from their collection based on their queries.
327
+
328
+ User Query:
329
+ {user_query}
330
+
331
+ Bookmarks:
332
+ {bookmark_data}
333
+
334
+ 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.
335
+ """
336
+
337
+ # Call the Groq Cloud API via the OpenAI client
338
+ response = openai.ChatCompletion.create(
339
+ model='llama3-8b-8192', # Specify the Groq Cloud model
340
+ messages=[
341
+ {"role": "system", "content": "You help users find relevant bookmarks based on their queries."},
342
+ {"role": "user", "content": prompt}
343
+ ],
344
+ max_tokens=500,
345
+ temperature=0.7,
346
+ )
347
+
348
+ # Extract the response text
349
+ answer = response['choices'][0]['message']['content'].strip()
350
+ logger.info("Chatbot response generated using Groq Cloud API")
351
+ return answer
352
 
353
  except Exception as e:
354
  logger.error(f"Error in chatbot response generation: {e}")
 
432
 
433
  # Build the Gradio app
434
  def build_app():
435
+ try:
436
+ logger.info("Building Gradio app")
437
+ with gr.Blocks(css="app.css") as demo:
438
+ gr.Markdown("<h1>Bookmark Manager App</h1>")
439
+
440
+ with gr.Tab("Upload and Process Bookmarks"):
441
+ upload = gr.File(label="Upload Bookmarks HTML File", type='binary')
442
+ process_button = gr.Button("Process Bookmarks")
443
+ output_text = gr.Textbox(label="Output")
444
+ bookmark_display = gr.HTML(label="Bookmarks")
445
+
446
+ def update_bookmark_display(file):
447
+ return process_uploaded_file(file)
448
+
449
+ process_button.click(
450
+ update_bookmark_display,
451
+ inputs=upload,
452
+ outputs=[output_text, bookmark_display]
453
+ )
454
+
455
+ with gr.Tab("Chat with Bookmarks"):
456
+ user_input = gr.Textbox(label="Ask about your bookmarks")
457
+ chat_output = gr.Textbox(label="Chatbot Response")
458
+ chat_button = gr.Button("Send")
459
+
460
+ chat_button.click(
461
+ chatbot_response,
462
+ inputs=user_input,
463
+ outputs=chat_output
464
+ )
465
+
466
+ with gr.Tab("Manage Bookmarks"):
467
+ manage_output = gr.Textbox(label="Manage Output")
468
+ bookmark_display_manage = gr.HTML(label="Bookmarks")
469
+ refresh_button = gr.Button("Refresh Bookmark List")
470
+
471
+ indices_input = gr.Textbox(label="Bookmark Indices to Delete (comma-separated)")
472
+ delete_button = gr.Button("Delete Selected Bookmarks")
473
+ export_button = gr.Button("Export Bookmarks")
474
+ download_link = gr.HTML(label="Download Exported Bookmarks")
475
+
476
+ with gr.Row():
477
+ index_input = gr.Number(label="Bookmark Index (Starting from 1)", precision=0)
478
+ new_title_input = gr.Textbox(label="New Title")
479
+ new_url_input = gr.Textbox(label="New URL")
480
+ new_category_input = gr.Dropdown(label="New Category", choices=CATEGORIES)
481
+
482
+ edit_button = gr.Button("Edit Bookmark")
483
+
484
+ def update_manage_display():
485
+ return display_bookmarks()
486
+
487
+ refresh_button.click(
488
+ update_manage_display,
489
+ inputs=None,
490
+ outputs=bookmark_display_manage
491
+ )
492
+
493
+ edit_button.click(
494
+ edit_bookmark,
495
+ inputs=[index_input, new_title_input, new_url_input, new_category_input],
496
+ outputs=[manage_output, bookmark_display_manage]
497
+ )
498
+
499
+ delete_button.click(
500
+ delete_bookmarks,
501
+ inputs=indices_input,
502
+ outputs=[manage_output, bookmark_display_manage]
503
+ )
504
+
505
+ def provide_download_link():
506
+ href = export_bookmarks()
507
+ if href:
508
+ return f'<a href="{href}" download="bookmarks.html">Download Exported Bookmarks</a>'
509
+ else:
510
+ return "No bookmarks to export."
511
+
512
+ export_button.click(
513
+ provide_download_link,
514
+ inputs=None,
515
+ outputs=download_link
516
+ )
517
+
518
+ # Initial load of the bookmarks display
519
+ bookmark_display_manage.value = update_manage_display()
520
+
521
+ logger.info("Launching Gradio app")
522
+ demo.launch(debug=True)
523
+ except Exception as e:
524
+ logger.error(f"Error building the app: {e}")
525
+ print(f"Error building the app: {e}")
526
 
527
  if __name__ == "__main__":
528
  build_app()