Skip to content

AugustLigh/RanobeLibLight

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“š RanobeLibLight

A lightweight and elegant Python library for RanobeLib API

Python Version License Code Style

✨ Features

  • πŸš€ Simple and intuitive API - Search("query") just works
  • πŸ“– Complete chapter and volume management
  • πŸ” Powerful catalog search with pagination
  • πŸ›‘οΈ Error handling with custom exceptions
  • πŸ“ Full type hints support
  • 🎯 Minimal dependencies (only requests)
  • 🐍 Python 3.7+ support

πŸ“¦ Installation

pip install requests

Clone and install:

git clone https://github.com/AugustLigh/RanobeLibLight
cd ranobelib
pip install -e .

πŸš€ Quick Start

Search for ranobe

from ranobeliblight import Search

# Simple search - one line!
results = Search("daughter of evil")

# Iterate over results
for manga in results[:5]:
    print(f"{manga.rus_name} - {manga.rating.averageFormated}β˜…")
    print(f"  Status: {manga.status.label}")
    print(f"  URL: {manga.url}\n")

Work with ranobe

from ranobeliblight import Ranobe

# Create ranobe object (use slug from URL)
ranobe = Ranobe('41368--nemurase-hime-kara-no-gifuto')

# Get info
print(f"Title: {ranobe.title}")

# Get chapters
chapters = ranobe.get_chapters()
print(f"Total chapters: {len(chapters)}")

# Filter chapters
chapters_vol_1 = chapters.filter_by_volume('1')
chapters_range = chapters.filter_by_number_range(1, 10)

# Get chapter content
chapter = chapters[0]
content = ranobe.get_chapter_content(chapter.number, chapter.volume)
text = content.get_text()

print(f"\n{chapter.name}")
print(f"Words: {content.word_count}, Characters: {content.char_count}")
print(f"\n{text[:500]}...")

Export chapters to file

from ranobeliblight import Ranobe

ranobe = Ranobe('41368--nemurase-hime-kara-no-gifuto')

# Get chapters
chapters = ranobe.get_chapters()
filtered = chapters.filter_by_number_range(1, 10)

# Save to text file
with open('chapters.txt', 'w', encoding='utf-8') as f:
    for chapter in filtered:
        content = ranobe.get_chapter_content(chapter.number, chapter.volume)
        
        f.write(f"\n{'='*60}\n")
        f.write(f"{chapter.name}\n")
        f.write(f"Volume {chapter.volume}, Chapter {chapter.number}\n")
        f.write(f"{'='*60}\n\n")
        f.write(content.get_text())
        f.write("\n\n")

πŸ“– API Reference

Search(query, page=1, per_page=20)

Quick search function - the simplest way to search!

from ranobeliblight import Search

# Simple search
results = Search("magic")

# With pagination
page_2 = Search("magic", page=2, per_page=10)

Returns: SearchResponse object


Search class

Advanced search with more control.

from ranobeliblight import Search

# Create searcher
searcher = Search("magic")

# Get all pages
all_pages = searcher.all_pages("magic", max_pages=3)

Methods

Method Description Returns
__call__(query, page=1, per_page=20) Search by query SearchResponse
all_pages(query, max_pages=None) Search all pages List[SearchResponse]

Ranobe class

Main class for working with ranobe.

from ranobeliblight import Ranobe

ranobe = Ranobe('your-slug-here')

Methods

Method Description Returns
get_info(fields=None) Get ranobe information dict
get_chapters() Get all chapters ChaptersList
get_chapter_content(number, volume) Get chapter content ChapterContent
get_chapter_text(number, volume) Get chapter text str
get_chapter_by_index(index) Get chapter by index Chapter

Properties

Property Description
title Russian title
url Full URL on website

ChaptersList class

Chapters list with convenient filtering methods.

Methods

Method Description
filter_by_volume(volume) Filter by volume
filter_by_number_range(min, max) Filter by number range
get_by_number(number, volume=None) Get chapter by number
filter(predicate) Filter by custom condition
get_volumes() Get list of volumes
group_by_volume() Group chapters by volume

Examples:

chapters = ranobe.get_chapters()

# Filtering
vol_2 = chapters.filter_by_volume('2')
first_10 = chapters.filter_by_number_range(1, 10)
custom = chapters.filter(lambda ch: float(ch.volume) > 1)

# Grouping
by_volume = chapters.group_by_volume()
for vol, chs in by_volume.items():
    print(f"Volume {vol}: {len(chs)} chapters")

ChapterContent class

Chapter content.

Methods

Method Description
get_text(separator="\n") Get all text
get_paragraphs() Get list of paragraphs

Properties

Property Description
word_count Word count
char_count Character count

Exceptions

The library provides specialized exceptions:

from ranobeliblight import (
    RanobeLibException,      # Base exception
    RanobeNotFoundError,     # Ranobe not found
    ChapterNotFoundError,    # Chapter not found
    APIError,                # API error
    NetworkError,            # Network error
    InvalidParameterError    # Invalid parameter
)

try:
    ranobe = Ranobe('invalid-id')
    info = ranobe.get_info()
except RanobeNotFoundError as e:
    print(f"Ranobe not found: {e}")
except NetworkError as e:
    print(f"Network problem: {e}")

🎯 Advanced Usage

Custom session with timeout

from ranobeliblight import Ranobe, RanobeSession

# Create session with custom timeout
session = RanobeSession(timeout=60)
ranobe = Ranobe('your-slug', session=session)

Pagination in search

from ranobeliblight import Search

# Paginated search using function
page_1 = Search("magic", page=1, per_page=10)
page_2 = Search("magic", page=2, per_page=10)

# Or get all pages at once using class
searcher = Search()
all_pages = searcher.all_pages("magic", max_pages=3)
all_results = [result for page in all_pages for result in page]

Batch chapter download

from ranobeliblight import Ranobe
import time

ranobe = Ranobe('your-slug')
chapters = ranobe.get_chapters()

for i, chapter in enumerate(chapters, 1):
    try:
        content = ranobe.get_chapter_content(chapter.number, chapter.volume)
        
        # Save
        filename = f"chapter_{chapter.number}.txt"
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(content.get_text())
        
        print(f"[{i}/{len(chapters)}] βœ“ {chapter.name}")
        
        # Small delay to avoid overloading API
        time.sleep(0.5)
        
    except Exception as e:
        print(f"[{i}/{len(chapters)}] βœ— Error: {e}")

Export to RTF

from ranobeliblight import Ranobe

def escape_rtf(text):
    """Escape special characters for RTF"""
    result = ""
    for char in text:
        code = ord(char)
        if code < 128:
            if char == '\\':
                result += '\\\\'
            elif char == '{':
                result += '\\{'
            elif char == '}':
                result += '\\}'
            elif char == '\n':
                result += '\\par\n'
            else:
                result += char
        else:
            result += f'\\u{code}?'
    return result

# Create RTF document
ranobe = Ranobe('41368--nemurase-hime-kara-no-gifuto')
chapters = ranobe.get_chapters()

rtf_content = r"""{\rtf1\ansi\ansicpg1251\deff0
{\fonttbl{\f0\fnil\fcharset204 Times New Roman;}}
\viewkind4\uc1\pard\lang1049\f0\fs24
"""

for chapter in chapters[:10]:  # First 10 chapters
    content = ranobe.get_chapter_content(chapter.number, chapter.volume)
    
    # Add title
    rtf_content += r"\b\fs28 " + escape_rtf(chapter.name) + r"\b0\fs24\par\par" + "\n"
    
    # Add text
    rtf_content += escape_rtf(content.get_text()) + "\n\\page\n"

rtf_content += "}"

# Save
with open('output.rtf', 'w', encoding='ascii') as f:
    f.write(rtf_content)

πŸ”§ Project Structure

ranobeliblight/
β”œβ”€β”€ __init__.py           # Main module with exports
β”œβ”€β”€ ranobe.py            # Ranobe class
β”œβ”€β”€ search.py            # Search class and function
β”œβ”€β”€ constant.py          # Session and constants
β”œβ”€β”€ exceptions.py        # Exceptions
└── models/              # Data models
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ chapters.py      # Chapter models
    β”œβ”€β”€ chapter_content.py  # Content models
    └── search.py        # Search models

πŸ’‘ Tips and Best Practices

  1. Use chapter filtering for working with large ranobe
  2. Add delays when bulk downloading (use time.sleep())
  3. Handle exceptions for reliable operation
  4. Cache results if making many requests
  5. Use get_chapter_text() if you only need text without metadata

🀝 Examples

More examples in the project folder:

  • example.py - Export to RTF
  • example_search.py - Search examples
  • example_usage.py - Get ranobe information
  • search_download.py - Search and download in one file

⚠️ Limitations

  • API may have rate limiting - add delays between requests
  • Some ranobe may be unavailable or require authentication
  • Content format may vary depending on source

πŸ“„ License

MIT License - use freely!

πŸ™ Acknowledgments

Thanks to RanobeLib for the API and all ranobe readers! πŸ“šβœ¨


Made with ❀️ for ranobe lovers

About

Api for ranobelib.me site.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages