Giter VIP home page Giter VIP logo

paulpierre / markdown-crawler Goto Github PK

View Code? Open in Web Editor NEW
256.0 4.0 27.0 1.16 MB

A multithreaded πŸ•ΈοΈ web crawler that recursively crawls a website and creates a πŸ”½ markdown file for each page, designed for LLM RAG

Home Page: https://pypi.org/project/markdown-crawler/

License: MIT License

Python 100.00%
html-to-markdown html-to-markdown-converter html2md llm llmops markdown markdown-parser rag web-scraper markdown-crawler

markdown-crawler's Introduction

                |                                     |             
 __ `__ \    _` |        __|   __|   _` | \ \  \   /  |   _ \   __| 
 |   |   |  (   |       (     |     (   |  \ \  \ /   |   __/  |    
_|  _|  _| \__._|      \___| _|    \__._|   \_/\_/   _| \___| _|    

---------------------------------
markdown_crawler - by @paulpierre
---------------------------------
A multithreaded πŸ•ΈοΈ web crawler that recursively crawls a website and creates a πŸ”½ markdown file for each page
https://github.com/paulpierre
https://x.com/paulpierre                                                        



πŸ“ Overview

This is a multithreaded web crawler that crawls a website and creates markdown files for each page. It was primarily created for large language model document parsing to simplify chunking and processing of large documents for RAG use cases. Markdown by nature is human readable and maintains document structure while keeping a small footprint.

✨ Features include

  • 🧡 Threading support for faster crawling
  • ⏯️ Continue scraping where you left off
  • ⏬ Set the max depth of children you wish to crawl
  • πŸ“„ Support for tables, images, etc.
  • βœ… Validates URLs, HTML, filepaths
  • βš™οΈ Configure list of valid base paths or base domains
  • 🍲 Uses BeautifulSoup to parse HTML
  • πŸͺ΅ Verbose logging option
  • πŸ‘©β€πŸ’» Ready-to-go CLI interface

πŸ—οΈ Use cases

  • RAG (retrieval augmented generation) - my primary usecase, use this to normalize large documents and chunk by header, pargraph or sentence
  • LLM fine-tuning - Create a large corpus of markdown files as a first step and leverage gpt-3.5-turbo or Mistral-7B to extract Q&A pairs
  • Agent knowledge - Leverage this with autogen for expert agents, for example if you wish to reconstruct the knowledge corpus of a videogame or movie, use this to generate the given expert corpus
  • Agent / LLM tools - Use this for online RAG learning so your chatbot continues to learn. Use SERP and scrape + index top N results w/ markdown-crawler
  • many more ..



πŸš€ Get started

If you wish to simply use it in the CLI, you can run the following command:

Install the package

pip install markdown-crawler

Execute the CLI

markdown-crawler -t 5 -d 3 -b ./markdown https://en.wikipedia.org/wiki/Morty_Smith

To run from the github repo, once you have it checked out:

pip install .
markdown-crawler -t 5 -d 3 -b ./markdown https://en.wikipedia.org/wiki/Morty_Smith

Or use the library in your own code:

from markdown_crawler import md_crawl
url = 'https://en.wikipedia.org/wiki/Morty_Smith'
md_crawl(url, max_depth=3, num_threads=5, base_path='markdown')



⚠️ Requirements

  • Python 3.x
  • BeautifulSoup4
  • requests
  • markdownify



πŸ” Usage

The following arguments are supported

usage: markdown-crawler [-h] [--max-depth MAX_DEPTH] [--num-threads NUM_THREADS] [--base-path BASE_PATH] [--debug DEBUG]
                  [--target-content TARGET_CONTENT] [--target-links TARGET_LINKS] [--valid-paths VALID_PATHS]
                  [--domain-match DOMAIN_MATCH] [--base-path-match BASE_PATH_MATCH]
                  [--links ]
                  base-url



πŸ“ Example

Take a look at example.py for an example implementation of the library. In this configuration we set:

  • max_depth to 3. We will crawl the base URL and 3 levels of children
  • num_threads to 5. We will use 5 parallel(ish) threads to crawl the website
  • base_dir to markdown. We will save the markdown files in the markdown directory
  • valid_paths an array of valid relative URL paths. We will only crawl pages that are in this list and base path
  • target_content to div#content. We will only crawl pages that have this HTML element using CSS target selectors. You can provide multiple and it will concatenate the results
  • is_domain_match to False. We will only crawl pages that are in the same domain as the base URL
  • is_base_path_match to False. We will include all URLs in the same domain, even if they don't begin with the base url
  • is_debug to True. We will print out verbose logging

And when we run it we can view the progress

cli

We can see the progress of our files in the markdown directory locally

md

And we can see the contents of the HTML converted to markdown

md



❀️ Thanks

If you have any issues, please feel free to open an issue or submit a PR. You can reach me via DM on Twitter/X.



βš–οΈ License

MIT License Copyright (c) 2023 Paul Pierre Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.



markdownify credits

markdown_crawler makes use of markdownify by Matthew Tretter. The original source code can be found here. It is licensed under the MIT license.

markdown-crawler's People

Contributors

paulpierre avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

markdown-crawler's Issues

cannot access local variable 'main_content' where it is not associated with a value

i just ran into this issue when crawling https://docs.xendit.co/.

command:

markdown-crawler --max-depth 10 --num-threads 5 --base-dir ./xendit-docs --domain-match --base-path-match https://docs.xendit.co/

issue:

Exception in thread Thread-1 (worker):
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/threading.py", line 1052, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/threading.py", line 989, in run
    self._target(*self._args, **self._kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/markdown_crawler/__init__.py", line 255, in worker
    child_urls = crawl(
                 ^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/markdown_crawler/__init__.py", line 120, in crawl
    content = get_target_content(soup, target_content=target_content)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/markdown_crawler/__init__.py", line 184, in get_target_content
    content = str(main_content)
                  ^^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'main_content' where it is not associated with a value

Submitting this as an issue for now, but I may have contributions for you...

I hacked apart your code for hours to purpose-build a script for a project, & it actually ended up being possibly useful for other people for many other applications. I simply wanted to scrape an entire GitBook into markdown very quickly & easily to keep it up to date as training data. But it does a bang up job of cleaning up the text for many different things. I sicked it on developers.android.com & it does quite well. Another couple docs pages, & it is good... It's very much driven towards my own goals, but if anybody is interested, it is currently nested inside of another project here: https://github.com/symmetricalboy/myshell-assistant/tree/main/md-tool
I may clean it up & generalize it & fork you eventually, but not at the moment.
One bit of feedback after living in your code for so long: threading sucks. You should use async. But I didn't actually implement async myself yet, so...
Also, I am using turndown.js to clean the text now, which is much better.
Cheers!

Not all links are found when custom `target_content` is set.

I wanted to try out this package for an internal RAG presentation based on some of our company website data. Our website has the typical structure: header, main content and footer. Most of the links are in the header and footer part, but if I set target_content to only the main container, no links are getting found.

Is there a way to have all URLs collected outside of the container i ultimately want to parse into markdown? When i don't specify the target i am getting quite a mess of navigation and footer link data that repeats on every page (which would have to be cleaned up for every single page)..

Thanks in advance!


Edit: I think it was actually a combination of the domain, base path flags and the target content that returns zero results. once I removed all the extra flags, the target content worked as advertised.

Continue where you left off feature is not working robustly

I believe there's a problem when crawling massive documentation portals in a scenario where the crawler cannot handle a certain condition and exists suddenly, leading to the continuation task to start from the beginning but not intelligently, therefore leading to all the previous pages being checked before moving forward with the new download. This is my constant experience with stripe's documentation portal where every time after around an hour the crawler fails to move forward and there are no option to move forward exactly where you left off.
my suggestion is to switch the default behavior to continue where you left off without previous check, since I assume what you're doing with the current implantation is to also detect if there any changes and apply them as well on the existing files instead of literally sticking to the current state of the progress and attempting to finish the crawl job which is taking massive times.

UnicodeEncodeError : 'charmap' codec can't encode characters in position 2473-2474: character maps to

The error occurs in the crawl function in the init.py file, specifically in the section where markdown content is written to a file. Here is the relevant code excerpt:

# line 140 
with open(file_path, 'w') as f:
    f.write(output)

To resolve this issue, I suggest specifying the encoding when opening the file for writing. Here is the corrected code:

with open(file_path, 'w', encoding='utf-8') as f:
    f.write(output)

By adding encoding='utf-8' to the open() function, Python will use UTF-8 encoding when writing the file, which should prevent the UnicodeEncodeError.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.