oceansweep commited on
Commit
34fa93e
1 Parent(s): 3db5f53

Update App_Function_Libraries/Gradio_UI/Website_scraping_tab.py

Browse files
App_Function_Libraries/Gradio_UI/Website_scraping_tab.py CHANGED
@@ -1,554 +1,554 @@
1
- # Website_scraping_tab.py
2
- # Gradio UI for scraping websites
3
- #
4
- # Imports
5
- import asyncio
6
- import json
7
- import logging
8
- import os
9
- import random
10
- from concurrent.futures import ThreadPoolExecutor
11
- from typing import Optional, List, Dict, Any
12
- from urllib.parse import urlparse, urljoin
13
-
14
- #
15
- # External Imports
16
- import gradio as gr
17
- from playwright.async_api import TimeoutError, async_playwright
18
- from playwright.sync_api import sync_playwright
19
-
20
- #
21
- # Local Imports
22
- from App_Function_Libraries.Web_Scraping.Article_Extractor_Lib import scrape_from_sitemap, scrape_by_url_level, scrape_article
23
- from App_Function_Libraries.Web_Scraping.Article_Summarization_Lib import scrape_and_summarize_multiple
24
- from App_Function_Libraries.DB.DB_Manager import load_preset_prompts
25
- from App_Function_Libraries.Gradio_UI.Chat_ui import update_user_prompt
26
- from App_Function_Libraries.Summarization.Summarization_General_Lib import summarize
27
-
28
-
29
- #
30
- ########################################################################################################################
31
- #
32
- # Functions:
33
-
34
- def get_url_depth(url: str) -> int:
35
- return len(urlparse(url).path.strip('/').split('/'))
36
-
37
-
38
- def sync_recursive_scrape(url_input, max_pages, max_depth, progress_callback, delay=1.0):
39
- def run_async_scrape():
40
- loop = asyncio.new_event_loop()
41
- asyncio.set_event_loop(loop)
42
- return loop.run_until_complete(
43
- recursive_scrape(url_input, max_pages, max_depth, progress_callback, delay)
44
- )
45
-
46
- with ThreadPoolExecutor() as executor:
47
- future = executor.submit(run_async_scrape)
48
- return future.result()
49
-
50
-
51
- async def recursive_scrape(
52
- base_url: str,
53
- max_pages: int,
54
- max_depth: int,
55
- progress_callback: callable,
56
- delay: float = 1.0,
57
- resume_file: str = 'scrape_progress.json',
58
- user_agent: str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
59
- ) -> List[Dict]:
60
- async def save_progress():
61
- temp_file = resume_file + ".tmp"
62
- with open(temp_file, 'w') as f:
63
- json.dump({
64
- 'visited': list(visited),
65
- 'to_visit': to_visit,
66
- 'scraped_articles': scraped_articles,
67
- 'pages_scraped': pages_scraped
68
- }, f)
69
- os.replace(temp_file, resume_file) # Atomic replace
70
-
71
- def is_valid_url(url: str) -> bool:
72
- return url.startswith("http") and len(url) > 0
73
-
74
- # Load progress if resume file exists
75
- if os.path.exists(resume_file):
76
- with open(resume_file, 'r') as f:
77
- progress_data = json.load(f)
78
- visited = set(progress_data['visited'])
79
- to_visit = progress_data['to_visit']
80
- scraped_articles = progress_data['scraped_articles']
81
- pages_scraped = progress_data['pages_scraped']
82
- else:
83
- visited = set()
84
- to_visit = [(base_url, 0)] # (url, depth)
85
- scraped_articles = []
86
- pages_scraped = 0
87
-
88
- try:
89
- async with async_playwright() as p:
90
- browser = await p.chromium.launch(headless=True)
91
- context = await browser.new_context(user_agent=user_agent)
92
-
93
- try:
94
- while to_visit and pages_scraped < max_pages:
95
- current_url, current_depth = to_visit.pop(0)
96
-
97
- if current_url in visited or current_depth > max_depth:
98
- continue
99
-
100
- visited.add(current_url)
101
-
102
- # Update progress
103
- progress_callback(f"Scraping page {pages_scraped + 1}/{max_pages}: {current_url}")
104
-
105
- try:
106
- await asyncio.sleep(random.uniform(delay * 0.8, delay * 1.2))
107
-
108
- # This function should be implemented to handle asynchronous scraping
109
- article_data = await scrape_article_async(context, current_url)
110
-
111
- if article_data and article_data['extraction_successful']:
112
- scraped_articles.append(article_data)
113
- pages_scraped += 1
114
-
115
- # If we haven't reached max depth, add child links to to_visit
116
- if current_depth < max_depth:
117
- page = await context.new_page()
118
- await page.goto(current_url)
119
- await page.wait_for_load_state("networkidle")
120
-
121
- links = await page.eval_on_selector_all('a[href]',
122
- "(elements) => elements.map(el => el.href)")
123
- for link in links:
124
- child_url = urljoin(base_url, link)
125
- if is_valid_url(child_url) and child_url.startswith(
126
- base_url) and child_url not in visited and should_scrape_url(child_url):
127
- to_visit.append((child_url, current_depth + 1))
128
-
129
- await page.close()
130
-
131
- except Exception as e:
132
- logging.error(f"Error scraping {current_url}: {str(e)}")
133
-
134
- # Save progress periodically (e.g., every 10 pages)
135
- if pages_scraped % 10 == 0:
136
- await save_progress()
137
-
138
- finally:
139
- await browser.close()
140
-
141
- finally:
142
- # These statements are now guaranteed to be reached after the scraping is done
143
- await save_progress()
144
-
145
- # Remove the progress file when scraping is completed successfully
146
- if os.path.exists(resume_file):
147
- os.remove(resume_file)
148
-
149
- # Final progress update
150
- progress_callback(f"Scraping completed. Total pages scraped: {pages_scraped}")
151
-
152
- return scraped_articles
153
-
154
-
155
- async def scrape_article_async(context, url: str) -> Dict[str, Any]:
156
- page = await context.new_page()
157
- try:
158
- await page.goto(url)
159
- await page.wait_for_load_state("networkidle")
160
-
161
- title = await page.title()
162
- content = await page.content()
163
-
164
- return {
165
- 'url': url,
166
- 'title': title,
167
- 'content': content,
168
- 'extraction_successful': True
169
- }
170
- except Exception as e:
171
- logging.error(f"Error scraping article {url}: {str(e)}")
172
- return {
173
- 'url': url,
174
- 'extraction_successful': False,
175
- 'error': str(e)
176
- }
177
- finally:
178
- await page.close()
179
-
180
-
181
- def scrape_article_sync(url: str) -> Dict[str, Any]:
182
- with sync_playwright() as p:
183
- browser = p.chromium.launch(headless=True)
184
- page = browser.new_page()
185
- try:
186
- page.goto(url)
187
- page.wait_for_load_state("networkidle")
188
-
189
- title = page.title()
190
- content = page.content()
191
-
192
- return {
193
- 'url': url,
194
- 'title': title,
195
- 'content': content,
196
- 'extraction_successful': True
197
- }
198
- except Exception as e:
199
- logging.error(f"Error scraping article {url}: {str(e)}")
200
- return {
201
- 'url': url,
202
- 'extraction_successful': False,
203
- 'error': str(e)
204
- }
205
- finally:
206
- browser.close()
207
-
208
-
209
- def should_scrape_url(url: str) -> bool:
210
- parsed_url = urlparse(url)
211
- path = parsed_url.path.lower()
212
-
213
- # List of patterns to exclude
214
- exclude_patterns = [
215
- '/tag/', '/category/', '/author/', '/search/', '/page/',
216
- 'wp-content', 'wp-includes', 'wp-json', 'wp-admin',
217
- 'login', 'register', 'cart', 'checkout', 'account',
218
- '.jpg', '.png', '.gif', '.pdf', '.zip'
219
- ]
220
-
221
- # Check if the URL contains any exclude patterns
222
- if any(pattern in path for pattern in exclude_patterns):
223
- return False
224
-
225
- # Add more sophisticated checks here
226
- # For example, you might want to only include URLs with certain patterns
227
- include_patterns = ['/article/', '/post/', '/blog/']
228
- if any(pattern in path for pattern in include_patterns):
229
- return True
230
-
231
- # By default, return True if no exclusion or inclusion rules matched
232
- return True
233
-
234
-
235
- async def scrape_with_retry(url: str, max_retries: int = 3, retry_delay: float = 5.0):
236
- for attempt in range(max_retries):
237
- try:
238
- return await scrape_article(url)
239
- except TimeoutError:
240
- if attempt < max_retries - 1:
241
- logging.warning(f"Timeout error scraping {url}. Retrying in {retry_delay} seconds...")
242
- await asyncio.sleep(retry_delay)
243
- else:
244
- logging.error(f"Failed to scrape {url} after {max_retries} attempts.")
245
- return None
246
- except Exception as e:
247
- logging.error(f"Error scraping {url}: {str(e)}")
248
- return None
249
-
250
-
251
- def create_website_scraping_tab():
252
- with gr.TabItem("Website Scraping", visible=True):
253
- gr.Markdown("# Scrape Websites & Summarize Articles")
254
- with gr.Row():
255
- with gr.Column():
256
- scrape_method = gr.Radio(
257
- ["Individual URLs", "Sitemap", "URL Level", "Recursive Scraping"],
258
- label="Scraping Method",
259
- value="Individual URLs"
260
- )
261
- url_input = gr.Textbox(
262
- label="Article URLs or Base URL",
263
- placeholder="Enter article URLs here, one per line, or base URL for sitemap/URL level/recursive scraping",
264
- lines=5
265
- )
266
- url_level = gr.Slider(
267
- minimum=1,
268
- maximum=10,
269
- step=1,
270
- label="URL Level (for URL Level scraping)",
271
- value=2,
272
- visible=False
273
- )
274
- max_pages = gr.Slider(
275
- minimum=1,
276
- maximum=100,
277
- step=1,
278
- label="Maximum Pages to Scrape (for Recursive Scraping)",
279
- value=10,
280
- visible=False
281
- )
282
- max_depth = gr.Slider(
283
- minimum=1,
284
- maximum=10,
285
- step=1,
286
- label="Maximum Depth (for Recursive Scraping)",
287
- value=3,
288
- visible=False
289
- )
290
- custom_article_title_input = gr.Textbox(
291
- label="Custom Article Titles (Optional, one per line)",
292
- placeholder="Enter custom titles for the articles, one per line",
293
- lines=5
294
- )
295
- with gr.Row():
296
- summarize_checkbox = gr.Checkbox(label="Summarize Articles", value=False)
297
- custom_prompt_checkbox = gr.Checkbox(label="Use a Custom Prompt", value=False, visible=True)
298
- preset_prompt_checkbox = gr.Checkbox(label="Use a pre-set Prompt", value=False, visible=True)
299
- with gr.Row():
300
- temp_slider = gr.Slider(0.1, 2.0, 0.7, label="Temperature")
301
- with gr.Row():
302
- preset_prompt = gr.Dropdown(
303
- label="Select Preset Prompt",
304
- choices=load_preset_prompts(),
305
- visible=False
306
- )
307
- with gr.Row():
308
- website_custom_prompt_input = gr.Textbox(
309
- label="Custom Prompt",
310
- placeholder="Enter custom prompt here",
311
- lines=3,
312
- visible=False
313
- )
314
- with gr.Row():
315
- system_prompt_input = gr.Textbox(
316
- label="System Prompt",
317
- value="""<s>You are a bulleted notes specialist. [INST]```When creating comprehensive bulleted notes, you should follow these guidelines: Use multiple headings based on the referenced topics, not categories like quotes or terms. Headings should be surrounded by bold formatting and not be listed as bullet points themselves. Leave no space between headings and their corresponding list items underneath. Important terms within the content should be emphasized by setting them in bold font. Any text that ends with a colon should also be bolded. Before submitting your response, review the instructions, and make any corrections necessary to adhered to the specified format. Do not reference these instructions within the notes.``` \nBased on the content between backticks create comprehensive bulleted notes.[/INST]
318
- **Bulleted Note Creation Guidelines**
319
-
320
- **Headings**:
321
- - Based on referenced topics, not categories like quotes or terms
322
- - Surrounded by **bold** formatting
323
- - Not listed as bullet points
324
- - No space between headings and list items underneath
325
-
326
- **Emphasis**:
327
- - **Important terms** set in bold font
328
- - **Text ending in a colon**: also bolded
329
-
330
- **Review**:
331
- - Ensure adherence to specified format
332
- - Do not reference these instructions in your response.</s>[INST] {{ .Prompt }} [/INST]
333
- """,
334
- lines=3,
335
- visible=False
336
- )
337
-
338
- api_name_input = gr.Dropdown(
339
- choices=[None, "Local-LLM", "OpenAI", "Anthropic", "Cohere", "Groq", "DeepSeek", "Mistral",
340
- "OpenRouter",
341
- "Llama.cpp", "Kobold", "Ooba", "Tabbyapi", "VLLM", "ollama", "HuggingFace",
342
- "Custom-OpenAI-API"],
343
- value=None,
344
- label="API Name (Mandatory for Summarization)"
345
- )
346
- api_key_input = gr.Textbox(
347
- label="API Key (Mandatory if API Name is specified)",
348
- placeholder="Enter your API key here; Ignore if using Local API or Built-in API",
349
- type="password"
350
- )
351
- keywords_input = gr.Textbox(
352
- label="Keywords",
353
- placeholder="Enter keywords here (comma-separated)",
354
- value="default,no_keyword_set",
355
- visible=True
356
- )
357
-
358
- scrape_button = gr.Button("Scrape and Summarize")
359
- with gr.Column():
360
- progress_output = gr.Textbox(label="Progress", lines=3)
361
- result_output = gr.Textbox(label="Result", lines=20)
362
-
363
- def update_ui_for_scrape_method(method):
364
- url_level_update = gr.update(visible=(method == "URL Level"))
365
- max_pages_update = gr.update(visible=(method == "Recursive Scraping"))
366
- max_depth_update = gr.update(visible=(method == "Recursive Scraping"))
367
- url_input_update = gr.update(
368
- label="Article URLs" if method == "Individual URLs" else "Base URL",
369
- placeholder="Enter article URLs here, one per line" if method == "Individual URLs" else "Enter the base URL for scraping"
370
- )
371
- return url_level_update, max_pages_update, max_depth_update, url_input_update
372
-
373
- scrape_method.change(
374
- fn=update_ui_for_scrape_method,
375
- inputs=[scrape_method],
376
- outputs=[url_level, max_pages, max_depth, url_input]
377
- )
378
-
379
- custom_prompt_checkbox.change(
380
- fn=lambda x: (gr.update(visible=x), gr.update(visible=x)),
381
- inputs=[custom_prompt_checkbox],
382
- outputs=[website_custom_prompt_input, system_prompt_input]
383
- )
384
- preset_prompt_checkbox.change(
385
- fn=lambda x: gr.update(visible=x),
386
- inputs=[preset_prompt_checkbox],
387
- outputs=[preset_prompt]
388
- )
389
-
390
- def update_prompts(preset_name):
391
- prompts = update_user_prompt(preset_name)
392
- return (
393
- gr.update(value=prompts["user_prompt"], visible=True),
394
- gr.update(value=prompts["system_prompt"], visible=True)
395
- )
396
-
397
- preset_prompt.change(
398
- update_prompts,
399
- inputs=preset_prompt,
400
- outputs=[website_custom_prompt_input, system_prompt_input]
401
- )
402
-
403
- async def scrape_and_summarize_wrapper(
404
- scrape_method: str,
405
- url_input: str,
406
- url_level: Optional[int],
407
- max_pages: int,
408
- max_depth: int,
409
- summarize_checkbox: bool,
410
- custom_prompt: Optional[str],
411
- api_name: Optional[str],
412
- api_key: Optional[str],
413
- keywords: str,
414
- custom_titles: Optional[str],
415
- system_prompt: Optional[str],
416
- temperature: float = 0.7,
417
- progress: gr.Progress = gr.Progress()
418
- ) -> str:
419
- try:
420
- result: List[Dict[str, Any]] = []
421
-
422
- if scrape_method == "Individual URLs":
423
- result = await scrape_and_summarize_multiple(url_input, custom_prompt, api_name, api_key, keywords,
424
- custom_titles, system_prompt)
425
- elif scrape_method == "Sitemap":
426
- result = await asyncio.to_thread(scrape_from_sitemap, url_input)
427
- elif scrape_method == "URL Level":
428
- if url_level is None:
429
- return convert_json_to_markdown(
430
- json.dumps({"error": "URL level is required for URL Level scraping."}))
431
- result = await asyncio.to_thread(scrape_by_url_level, url_input, url_level)
432
- elif scrape_method == "Recursive Scraping":
433
- result = await recursive_scrape(url_input, max_pages, max_depth, progress.update, delay=1.0)
434
- else:
435
- return convert_json_to_markdown(json.dumps({"error": f"Unknown scraping method: {scrape_method}"}))
436
-
437
- # Ensure result is always a list of dictionaries
438
- if isinstance(result, dict):
439
- result = [result]
440
- elif isinstance(result, list):
441
- if all(isinstance(item, str) for item in result):
442
- # Convert list of strings to list of dictionaries
443
- result = [{"content": item} for item in result]
444
- elif not all(isinstance(item, dict) for item in result):
445
- raise ValueError("Not all items in result are dictionaries or strings")
446
- else:
447
- raise ValueError(f"Unexpected result type: {type(result)}")
448
-
449
- # Ensure all items in result are dictionaries
450
- if not all(isinstance(item, dict) for item in result):
451
- raise ValueError("Not all items in result are dictionaries")
452
-
453
- if summarize_checkbox:
454
- total_articles = len(result)
455
- for i, article in enumerate(result):
456
- progress.update(f"Summarizing article {i + 1}/{total_articles}")
457
- content = article.get('content', '')
458
- if content:
459
- summary = await asyncio.to_thread(summarize, content, custom_prompt, api_name, api_key,
460
- temperature, system_prompt)
461
- article['summary'] = summary
462
- else:
463
- article['summary'] = "No content available to summarize."
464
-
465
- # Concatenate all content
466
- all_content = "\n\n".join(
467
- [f"# {article.get('title', 'Untitled')}\n\n{article.get('content', '')}\n\n" +
468
- (f"Summary: {article.get('summary', '')}" if summarize_checkbox else "")
469
- for article in result])
470
-
471
- # Collect all unique URLs
472
- all_urls = list(set(article.get('url', '') for article in result if article.get('url')))
473
-
474
- # Structure the output for the entire website collection
475
- website_collection = {
476
- "base_url": url_input,
477
- "scrape_method": scrape_method,
478
- "summarization_performed": summarize_checkbox,
479
- "api_used": api_name if summarize_checkbox else None,
480
- "keywords": keywords if summarize_checkbox else None,
481
- "url_level": url_level if scrape_method == "URL Level" else None,
482
- "max_pages": max_pages if scrape_method == "Recursive Scraping" else None,
483
- "max_depth": max_depth if scrape_method == "Recursive Scraping" else None,
484
- "total_articles_scraped": len(result),
485
- "urls_scraped": all_urls,
486
- "content": all_content
487
- }
488
-
489
- # Convert the JSON to markdown and return
490
- return convert_json_to_markdown(json.dumps(website_collection, indent=2))
491
- except Exception as e:
492
- return convert_json_to_markdown(json.dumps({"error": f"An error occurred: {str(e)}"}))
493
-
494
- # Update the scrape_button.click to include the temperature parameter
495
- scrape_button.click(
496
- fn=lambda *args: asyncio.run(scrape_and_summarize_wrapper(*args)),
497
- inputs=[scrape_method, url_input, url_level, max_pages, max_depth, summarize_checkbox,
498
- website_custom_prompt_input, api_name_input, api_key_input, keywords_input,
499
- custom_article_title_input, system_prompt_input, temp_slider],
500
- outputs=[result_output]
501
- )
502
-
503
-
504
- def convert_json_to_markdown(json_str: str) -> str:
505
- """
506
- Converts the JSON output from the scraping process into a markdown format.
507
-
508
- Args:
509
- json_str (str): JSON-formatted string containing the website collection data
510
-
511
- Returns:
512
- str: Markdown-formatted string of the website collection data
513
- """
514
- try:
515
- # Parse the JSON string
516
- data = json.loads(json_str)
517
-
518
- # Check if there's an error in the JSON
519
- if "error" in data:
520
- return f"# Error\n\n{data['error']}"
521
-
522
- # Start building the markdown string
523
- markdown = f"# Website Collection: {data['base_url']}\n\n"
524
-
525
- # Add metadata
526
- markdown += "## Metadata\n\n"
527
- markdown += f"- **Scrape Method:** {data['scrape_method']}\n"
528
- markdown += f"- **API Used:** {data['api_used']}\n"
529
- markdown += f"- **Keywords:** {data['keywords']}\n"
530
- if data['url_level'] is not None:
531
- markdown += f"- **URL Level:** {data['url_level']}\n"
532
- markdown += f"- **Total Articles Scraped:** {data['total_articles_scraped']}\n\n"
533
-
534
- # Add URLs scraped
535
- markdown += "## URLs Scraped\n\n"
536
- for url in data['urls_scraped']:
537
- markdown += f"- {url}\n"
538
- markdown += "\n"
539
-
540
- # Add the content
541
- markdown += "## Content\n\n"
542
- markdown += data['content']
543
-
544
- return markdown
545
-
546
- except json.JSONDecodeError:
547
- return "# Error\n\nInvalid JSON string provided."
548
- except KeyError as e:
549
- return f"# Error\n\nMissing key in JSON data: {str(e)}"
550
- except Exception as e:
551
- return f"# Error\n\nAn unexpected error occurred: {str(e)}"
552
- #
553
- # End of File
554
- ########################################################################################################################
 
1
+ # Website_scraping_tab.py
2
+ # Gradio UI for scraping websites
3
+ #
4
+ # Imports
5
+ import asyncio
6
+ import json
7
+ import logging
8
+ import os
9
+ import random
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from typing import Optional, List, Dict, Any
12
+ from urllib.parse import urlparse, urljoin
13
+
14
+ #
15
+ # External Imports
16
+ import gradio as gr
17
+ from playwright.async_api import TimeoutError, async_playwright
18
+ from playwright.sync_api import sync_playwright
19
+
20
+ #
21
+ # Local Imports
22
+ from App_Function_Libraries.Web_Scraping.Article_Extractor_Lib import scrape_from_sitemap, scrape_by_url_level, scrape_article
23
+ from App_Function_Libraries.Web_Scraping.Article_Summarization_Lib import scrape_and_summarize_multiple
24
+ from App_Function_Libraries.DB.DB_Manager import load_preset_prompts
25
+ from App_Function_Libraries.Gradio_UI.Chat_ui import update_user_prompt
26
+ from App_Function_Libraries.Summarization.Summarization_General_Lib import summarize
27
+
28
+
29
+ #
30
+ ########################################################################################################################
31
+ #
32
+ # Functions:
33
+
34
+ def get_url_depth(url: str) -> int:
35
+ return len(urlparse(url).path.strip('/').split('/'))
36
+
37
+
38
+ def sync_recursive_scrape(url_input, max_pages, max_depth, progress_callback, delay=1.0):
39
+ def run_async_scrape():
40
+ loop = asyncio.new_event_loop()
41
+ asyncio.set_event_loop(loop)
42
+ return loop.run_until_complete(
43
+ recursive_scrape(url_input, max_pages, max_depth, progress_callback, delay)
44
+ )
45
+
46
+ with ThreadPoolExecutor() as executor:
47
+ future = executor.submit(run_async_scrape)
48
+ return future.result()
49
+
50
+
51
+ async def recursive_scrape(
52
+ base_url: str,
53
+ max_pages: int,
54
+ max_depth: int,
55
+ progress_callback: callable,
56
+ delay: float = 1.0,
57
+ resume_file: str = 'scrape_progress.json',
58
+ user_agent: str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
59
+ ) -> List[Dict]:
60
+ async def save_progress():
61
+ temp_file = resume_file + ".tmp"
62
+ with open(temp_file, 'w') as f:
63
+ json.dump({
64
+ 'visited': list(visited),
65
+ 'to_visit': to_visit,
66
+ 'scraped_articles': scraped_articles,
67
+ 'pages_scraped': pages_scraped
68
+ }, f)
69
+ os.replace(temp_file, resume_file) # Atomic replace
70
+
71
+ def is_valid_url(url: str) -> bool:
72
+ return url.startswith("http") and len(url) > 0
73
+
74
+ # Load progress if resume file exists
75
+ if os.path.exists(resume_file):
76
+ with open(resume_file, 'r') as f:
77
+ progress_data = json.load(f)
78
+ visited = set(progress_data['visited'])
79
+ to_visit = progress_data['to_visit']
80
+ scraped_articles = progress_data['scraped_articles']
81
+ pages_scraped = progress_data['pages_scraped']
82
+ else:
83
+ visited = set()
84
+ to_visit = [(base_url, 0)] # (url, depth)
85
+ scraped_articles = []
86
+ pages_scraped = 0
87
+
88
+ try:
89
+ async with async_playwright() as p:
90
+ browser = await p.chromium.launch(headless=True)
91
+ context = await browser.new_context(user_agent=user_agent)
92
+
93
+ try:
94
+ while to_visit and pages_scraped < max_pages:
95
+ current_url, current_depth = to_visit.pop(0)
96
+
97
+ if current_url in visited or current_depth > max_depth:
98
+ continue
99
+
100
+ visited.add(current_url)
101
+
102
+ # Update progress
103
+ progress_callback(f"Scraping page {pages_scraped + 1}/{max_pages}: {current_url}")
104
+
105
+ try:
106
+ await asyncio.sleep(random.uniform(delay * 0.8, delay * 1.2))
107
+
108
+ # This function should be implemented to handle asynchronous scraping
109
+ article_data = await scrape_article_async(context, current_url)
110
+
111
+ if article_data and article_data['extraction_successful']:
112
+ scraped_articles.append(article_data)
113
+ pages_scraped += 1
114
+
115
+ # If we haven't reached max depth, add child links to to_visit
116
+ if current_depth < max_depth:
117
+ page = await context.new_page()
118
+ await page.goto(current_url)
119
+ await page.wait_for_load_state("networkidle")
120
+
121
+ links = await page.eval_on_selector_all('a[href]',
122
+ "(elements) => elements.map(el => el.href)")
123
+ for link in links:
124
+ child_url = urljoin(base_url, link)
125
+ if is_valid_url(child_url) and child_url.startswith(
126
+ base_url) and child_url not in visited and should_scrape_url(child_url):
127
+ to_visit.append((child_url, current_depth + 1))
128
+
129
+ await page.close()
130
+
131
+ except Exception as e:
132
+ logging.error(f"Error scraping {current_url}: {str(e)}")
133
+
134
+ # Save progress periodically (e.g., every 10 pages)
135
+ if pages_scraped % 10 == 0:
136
+ await save_progress()
137
+
138
+ finally:
139
+ await browser.close()
140
+
141
+ finally:
142
+ # These statements are now guaranteed to be reached after the scraping is done
143
+ await save_progress()
144
+
145
+ # Remove the progress file when scraping is completed successfully
146
+ if os.path.exists(resume_file):
147
+ os.remove(resume_file)
148
+
149
+ # Final progress update
150
+ progress_callback(f"Scraping completed. Total pages scraped: {pages_scraped}")
151
+
152
+ return scraped_articles
153
+
154
+
155
+ async def scrape_article_async(context, url: str) -> Dict[str, Any]:
156
+ page = await context.new_page()
157
+ try:
158
+ await page.goto(url)
159
+ await page.wait_for_load_state("networkidle")
160
+
161
+ title = await page.title()
162
+ content = await page.content()
163
+
164
+ return {
165
+ 'url': url,
166
+ 'title': title,
167
+ 'content': content,
168
+ 'extraction_successful': True
169
+ }
170
+ except Exception as e:
171
+ logging.error(f"Error scraping article {url}: {str(e)}")
172
+ return {
173
+ 'url': url,
174
+ 'extraction_successful': False,
175
+ 'error': str(e)
176
+ }
177
+ finally:
178
+ await page.close()
179
+
180
+
181
+ def scrape_article_sync(url: str) -> Dict[str, Any]:
182
+ with sync_playwright() as p:
183
+ browser = p.chromium.launch(headless=True)
184
+ page = browser.new_page()
185
+ try:
186
+ page.goto(url)
187
+ page.wait_for_load_state("networkidle")
188
+
189
+ title = page.title()
190
+ content = page.content()
191
+
192
+ return {
193
+ 'url': url,
194
+ 'title': title,
195
+ 'content': content,
196
+ 'extraction_successful': True
197
+ }
198
+ except Exception as e:
199
+ logging.error(f"Error scraping article {url}: {str(e)}")
200
+ return {
201
+ 'url': url,
202
+ 'extraction_successful': False,
203
+ 'error': str(e)
204
+ }
205
+ finally:
206
+ browser.close()
207
+
208
+
209
+ def should_scrape_url(url: str) -> bool:
210
+ parsed_url = urlparse(url)
211
+ path = parsed_url.path.lower()
212
+
213
+ # List of patterns to exclude
214
+ exclude_patterns = [
215
+ '/tag/', '/category/', '/author/', '/search/', '/page/',
216
+ 'wp-content', 'wp-includes', 'wp-json', 'wp-admin',
217
+ 'login', 'register', 'cart', 'checkout', 'account',
218
+ '.jpg', '.png', '.gif', '.pdf', '.zip'
219
+ ]
220
+
221
+ # Check if the URL contains any exclude patterns
222
+ if any(pattern in path for pattern in exclude_patterns):
223
+ return False
224
+
225
+ # Add more sophisticated checks here
226
+ # For example, you might want to only include URLs with certain patterns
227
+ include_patterns = ['/article/', '/post/', '/blog/']
228
+ if any(pattern in path for pattern in include_patterns):
229
+ return True
230
+
231
+ # By default, return True if no exclusion or inclusion rules matched
232
+ return True
233
+
234
+
235
+ async def scrape_with_retry(url: str, max_retries: int = 3, retry_delay: float = 5.0):
236
+ for attempt in range(max_retries):
237
+ try:
238
+ return await scrape_article(url)
239
+ except TimeoutError:
240
+ if attempt < max_retries - 1:
241
+ logging.warning(f"Timeout error scraping {url}. Retrying in {retry_delay} seconds...")
242
+ await asyncio.sleep(retry_delay)
243
+ else:
244
+ logging.error(f"Failed to scrape {url} after {max_retries} attempts.")
245
+ return None
246
+ except Exception as e:
247
+ logging.error(f"Error scraping {url}: {str(e)}")
248
+ return None
249
+
250
+
251
+ def create_website_scraping_tab():
252
+ with gr.TabItem("Website Scraping", visible=True):
253
+ gr.Markdown("# Scrape Websites & Summarize Articles")
254
+ with gr.Row():
255
+ with gr.Column():
256
+ scrape_method = gr.Radio(
257
+ ["Individual URLs", "Sitemap", "URL Level", "Recursive Scraping"],
258
+ label="Scraping Method",
259
+ value="Individual URLs"
260
+ )
261
+ url_input = gr.Textbox(
262
+ label="Article URLs or Base URL",
263
+ placeholder="Enter article URLs here, one per line, or base URL for sitemap/URL level/recursive scraping",
264
+ lines=5
265
+ )
266
+ url_level = gr.Slider(
267
+ minimum=1,
268
+ maximum=10,
269
+ step=1,
270
+ label="URL Level (for URL Level scraping)",
271
+ value=2,
272
+ visible=False
273
+ )
274
+ max_pages = gr.Slider(
275
+ minimum=1,
276
+ maximum=100,
277
+ step=1,
278
+ label="Maximum Pages to Scrape (for Recursive Scraping)",
279
+ value=10,
280
+ visible=False
281
+ )
282
+ max_depth = gr.Slider(
283
+ minimum=1,
284
+ maximum=10,
285
+ step=1,
286
+ label="Maximum Depth (for Recursive Scraping)",
287
+ value=3,
288
+ visible=False
289
+ )
290
+ custom_article_title_input = gr.Textbox(
291
+ label="Custom Article Titles (Optional, one per line)",
292
+ placeholder="Enter custom titles for the articles, one per line",
293
+ lines=5
294
+ )
295
+ with gr.Row():
296
+ summarize_checkbox = gr.Checkbox(label="Summarize Articles", value=False)
297
+ custom_prompt_checkbox = gr.Checkbox(label="Use a Custom Prompt", value=False, visible=True)
298
+ preset_prompt_checkbox = gr.Checkbox(label="Use a pre-set Prompt", value=False, visible=True)
299
+ with gr.Row():
300
+ temp_slider = gr.Slider(0.1, 2.0, 0.7, label="Temperature")
301
+ with gr.Row():
302
+ preset_prompt = gr.Dropdown(
303
+ label="Select Preset Prompt",
304
+ choices=load_preset_prompts(),
305
+ visible=False
306
+ )
307
+ with gr.Row():
308
+ website_custom_prompt_input = gr.Textbox(
309
+ label="Custom Prompt",
310
+ placeholder="Enter custom prompt here",
311
+ lines=3,
312
+ visible=False
313
+ )
314
+ with gr.Row():
315
+ system_prompt_input = gr.Textbox(
316
+ label="System Prompt",
317
+ value="""<s>You are a bulleted notes specialist. [INST]```When creating comprehensive bulleted notes, you should follow these guidelines: Use multiple headings based on the referenced topics, not categories like quotes or terms. Headings should be surrounded by bold formatting and not be listed as bullet points themselves. Leave no space between headings and their corresponding list items underneath. Important terms within the content should be emphasized by setting them in bold font. Any text that ends with a colon should also be bolded. Before submitting your response, review the instructions, and make any corrections necessary to adhered to the specified format. Do not reference these instructions within the notes.``` \nBased on the content between backticks create comprehensive bulleted notes.[/INST]
318
+ **Bulleted Note Creation Guidelines**
319
+
320
+ **Headings**:
321
+ - Based on referenced topics, not categories like quotes or terms
322
+ - Surrounded by **bold** formatting
323
+ - Not listed as bullet points
324
+ - No space between headings and list items underneath
325
+
326
+ **Emphasis**:
327
+ - **Important terms** set in bold font
328
+ - **Text ending in a colon**: also bolded
329
+
330
+ **Review**:
331
+ - Ensure adherence to specified format
332
+ - Do not reference these instructions in your response.</s>[INST] {{ .Prompt }} [/INST]
333
+ """,
334
+ lines=3,
335
+ visible=False
336
+ )
337
+
338
+ api_name_input = gr.Dropdown(
339
+ choices=[None, "Local-LLM", "OpenAI", "Anthropic", "Cohere", "Groq", "DeepSeek", "Mistral",
340
+ "OpenRouter",
341
+ "Llama.cpp", "Kobold", "Ooba", "Tabbyapi", "VLLM", "ollama", "HuggingFace",
342
+ "Custom-OpenAI-API"],
343
+ value=None,
344
+ label="API Name (Mandatory for Summarization)"
345
+ )
346
+ api_key_input = gr.Textbox(
347
+ label="API Key (Mandatory if API Name is specified)",
348
+ placeholder="Enter your API key here; Ignore if using Local API or Built-in API",
349
+ type="password"
350
+ )
351
+ keywords_input = gr.Textbox(
352
+ label="Keywords",
353
+ placeholder="Enter keywords here (comma-separated)",
354
+ value="default,no_keyword_set",
355
+ visible=True
356
+ )
357
+
358
+ scrape_button = gr.Button("Scrape and Summarize")
359
+ with gr.Column():
360
+ progress_output = gr.Textbox(label="Progress", lines=3)
361
+ result_output = gr.Textbox(label="Result", lines=20)
362
+
363
+ def update_ui_for_scrape_method(method):
364
+ url_level_update = gr.update(visible=(method == "URL Level"))
365
+ max_pages_update = gr.update(visible=(method == "Recursive Scraping"))
366
+ max_depth_update = gr.update(visible=(method == "Recursive Scraping"))
367
+ url_input_update = gr.update(
368
+ label="Article URLs" if method == "Individual URLs" else "Base URL",
369
+ placeholder="Enter article URLs here, one per line" if method == "Individual URLs" else "Enter the base URL for scraping"
370
+ )
371
+ return url_level_update, max_pages_update, max_depth_update, url_input_update
372
+
373
+ scrape_method.change(
374
+ fn=update_ui_for_scrape_method,
375
+ inputs=[scrape_method],
376
+ outputs=[url_level, max_pages, max_depth, url_input]
377
+ )
378
+
379
+ custom_prompt_checkbox.change(
380
+ fn=lambda x: (gr.update(visible=x), gr.update(visible=x)),
381
+ inputs=[custom_prompt_checkbox],
382
+ outputs=[website_custom_prompt_input, system_prompt_input]
383
+ )
384
+ preset_prompt_checkbox.change(
385
+ fn=lambda x: gr.update(visible=x),
386
+ inputs=[preset_prompt_checkbox],
387
+ outputs=[preset_prompt]
388
+ )
389
+
390
+ def update_prompts(preset_name):
391
+ prompts = update_user_prompt(preset_name)
392
+ return (
393
+ gr.update(value=prompts["user_prompt"], visible=True),
394
+ gr.update(value=prompts["system_prompt"], visible=True)
395
+ )
396
+
397
+ preset_prompt.change(
398
+ update_prompts,
399
+ inputs=preset_prompt,
400
+ outputs=[website_custom_prompt_input, system_prompt_input]
401
+ )
402
+
403
+ async def scrape_and_summarize_wrapper(
404
+ scrape_method: str,
405
+ url_input: str,
406
+ url_level: Optional[int],
407
+ max_pages: int,
408
+ max_depth: int,
409
+ summarize_checkbox: bool,
410
+ custom_prompt: Optional[str],
411
+ api_name: Optional[str],
412
+ api_key: Optional[str],
413
+ keywords: str,
414
+ custom_titles: Optional[str],
415
+ system_prompt: Optional[str],
416
+ temperature: float = 0.7,
417
+ progress: gr.Progress = gr.Progress()
418
+ ) -> str:
419
+ try:
420
+ result: List[Dict[str, Any]] = []
421
+
422
+ if scrape_method == "Individual URLs":
423
+ result = await scrape_and_summarize_multiple(url_input, custom_prompt, api_name, api_key, keywords,
424
+ custom_titles, system_prompt)
425
+ elif scrape_method == "Sitemap":
426
+ result = await asyncio.to_thread(scrape_from_sitemap, url_input)
427
+ elif scrape_method == "URL Level":
428
+ if url_level is None:
429
+ return convert_json_to_markdown(
430
+ json.dumps({"error": "URL level is required for URL Level scraping."}))
431
+ result = await asyncio.to_thread(scrape_by_url_level, url_input, url_level)
432
+ elif scrape_method == "Recursive Scraping":
433
+ result = await recursive_scrape(url_input, max_pages, max_depth, progress.update, delay=1.0)
434
+ else:
435
+ return convert_json_to_markdown(json.dumps({"error": f"Unknown scraping method: {scrape_method}"}))
436
+
437
+ # Ensure result is always a list of dictionaries
438
+ if isinstance(result, dict):
439
+ result = [result]
440
+ elif isinstance(result, list):
441
+ if all(isinstance(item, str) for item in result):
442
+ # Convert list of strings to list of dictionaries
443
+ result = [{"content": item} for item in result]
444
+ elif not all(isinstance(item, dict) for item in result):
445
+ raise ValueError("Not all items in result are dictionaries or strings")
446
+ else:
447
+ raise ValueError(f"Unexpected result type: {type(result)}")
448
+
449
+ # Ensure all items in result are dictionaries
450
+ if not all(isinstance(item, dict) for item in result):
451
+ raise ValueError("Not all items in result are dictionaries")
452
+
453
+ if summarize_checkbox:
454
+ total_articles = len(result)
455
+ for i, article in enumerate(result):
456
+ progress.update(f"Summarizing article {i + 1}/{total_articles}")
457
+ content = article.get('content', '')
458
+ if content:
459
+ summary = await asyncio.to_thread(summarize, content, custom_prompt, api_name, api_key,
460
+ temperature, system_prompt)
461
+ article['summary'] = summary
462
+ else:
463
+ article['summary'] = "No content available to summarize."
464
+
465
+ # Concatenate all content
466
+ all_content = "\n\n".join(
467
+ [f"# {article.get('title', 'Untitled')}\n\n{article.get('content', '')}\n\n" +
468
+ (f"Summary: {article.get('summary', '')}" if summarize_checkbox else "")
469
+ for article in result])
470
+
471
+ # Collect all unique URLs
472
+ all_urls = list(set(article.get('url', '') for article in result if article.get('url')))
473
+
474
+ # Structure the output for the entire website collection
475
+ website_collection = {
476
+ "base_url": url_input,
477
+ "scrape_method": scrape_method,
478
+ "summarization_performed": summarize_checkbox,
479
+ "api_used": api_name if summarize_checkbox else None,
480
+ "keywords": keywords if summarize_checkbox else None,
481
+ "url_level": url_level if scrape_method == "URL Level" else None,
482
+ "max_pages": max_pages if scrape_method == "Recursive Scraping" else None,
483
+ "max_depth": max_depth if scrape_method == "Recursive Scraping" else None,
484
+ "total_articles_scraped": len(result),
485
+ "urls_scraped": all_urls,
486
+ "content": all_content
487
+ }
488
+
489
+ # Convert the JSON to markdown and return
490
+ return convert_json_to_markdown(json.dumps(website_collection, indent=2))
491
+ except Exception as e:
492
+ return convert_json_to_markdown(json.dumps({"error": f"An error occurred: {str(e)}"}))
493
+
494
+ # Update the scrape_button.click to include the temperature parameter
495
+ scrape_button.click(
496
+ fn=lambda *args: asyncio.run(scrape_and_summarize_wrapper(*args)),
497
+ inputs=[scrape_method, url_input, url_level, max_pages, max_depth, summarize_checkbox,
498
+ website_custom_prompt_input, api_name_input, api_key_input, keywords_input,
499
+ custom_article_title_input, system_prompt_input, temp_slider],
500
+ outputs=[result_output]
501
+ )
502
+
503
+
504
+ def convert_json_to_markdown(json_str: str) -> str:
505
+ """
506
+ Converts the JSON output from the scraping process into a markdown format.
507
+
508
+ Args:
509
+ json_str (str): JSON-formatted string containing the website collection data
510
+
511
+ Returns:
512
+ str: Markdown-formatted string of the website collection data
513
+ """
514
+ try:
515
+ # Parse the JSON string
516
+ data = json.loads(json_str)
517
+
518
+ # Check if there's an error in the JSON
519
+ if "error" in data:
520
+ return f"# Error\n\n{data['error']}"
521
+
522
+ # Start building the markdown string
523
+ markdown = f"# Website Collection: {data['base_url']}\n\n"
524
+
525
+ # Add metadata
526
+ markdown += "## Metadata\n\n"
527
+ markdown += f"- **Scrape Method:** {data['scrape_method']}\n"
528
+ markdown += f"- **API Used:** {data['api_used']}\n"
529
+ markdown += f"- **Keywords:** {data['keywords']}\n"
530
+ if data['url_level'] is not None:
531
+ markdown += f"- **URL Level:** {data['url_level']}\n"
532
+ markdown += f"- **Total Articles Scraped:** {data['total_articles_scraped']}\n\n"
533
+
534
+ # Add URLs scraped
535
+ markdown += "## URLs Scraped\n\n"
536
+ for url in data['urls_scraped']:
537
+ markdown += f"- {url}\n"
538
+ markdown += "\n"
539
+
540
+ # Add the content
541
+ markdown += "## Content\n\n"
542
+ markdown += data['content']
543
+
544
+ return markdown
545
+
546
+ except json.JSONDecodeError:
547
+ return "# Error\n\nInvalid JSON string provided."
548
+ except KeyError as e:
549
+ return f"# Error\n\nMissing key in JSON data: {str(e)}"
550
+ except Exception as e:
551
+ return f"# Error\n\nAn unexpected error occurred: {str(e)}"
552
+ #
553
+ # End of File
554
+ ########################################################################################################################