File size: 9,677 Bytes
ed5026f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""
Project Gutenberg Downloader - Example Usage

This script demonstrates how to use the GutenbergDownloader to download
and process free e-books from Project Gutenberg.

Project Gutenberg URLs:
- https://www.gutenberg.org/ebooks/11 - Alice's Adventures in Wonderland
- https://www.gutenberg.org/ebooks/1342 - Pride and Prejudice
- https://www.gutenberg.org/ebooks/98 - A Tale of Two Cities
- https://www.gutenberg.org/ebooks/219 - Heart of Darkness
- https://www.gutenberg.org/ebooks/514 - Little Women
- https://www.gutenberg.org/ebooks/4300 - Ulysses
- https://www.gutenberg.org/ebooks/1661 - Sherlock Holmes - A Study in Scarlet
"""

import json
from pathlib import Path
from gutenberg_downloader import GutenbergDownloader


def example_1_single_book():
    """Example 1: Download and process a single book."""
    print("\n" + "=" * 70)
    print("Example 1: Download and Process a Single Book")
    print("=" * 70)

    downloader = GutenbergDownloader(cache_dir="./gutenberg_cache")

    # Download Alice in Wonderland
    book_url = "https://www.gutenberg.org/ebooks/11"
    print(f"\nDownloading from: {book_url}")

    content = downloader.download_book(book_url, format_type="text")

    if content:
        print(f"Downloaded {len(content)} characters")

        # Parse the book
        book_data = downloader.parse_text_book(content)

        print(f"\nBook Title: {book_data['title']}")
        print(f"Chapters found: {len(book_data['chapters'])}")
        print(f"Main text length: {len(book_data['main_text'])} characters")

        # Display first chapter
        if book_data['chapters']:
            print(f"\nFirst chapter: {book_data['chapters'][0]}")

        # Display first 500 characters of main text
        print(f"\nFirst 500 characters of main text:")
        print(book_data['main_text'][:500])

        # Save to file
        output_file = Path("./processed_books/alice.json")
        output_file.parent.mkdir(parents=True, exist_ok=True)
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(book_data, f, indent=2, ensure_ascii=False)
        print(f"\nSaved to: {output_file}")
    else:
        print("Failed to download book")


def example_2_multiple_books():
    """Example 2: Download and process multiple books."""
    print("\n" + "=" * 70)
    print("Example 2: Batch Download Multiple Books")
    print("=" * 70)

    downloader = GutenbergDownloader(cache_dir="./gutenberg_cache")

    # List of books to download
    books = [
        ("https://www.gutenberg.org/ebooks/11", "Alice in Wonderland"),
        ("https://www.gutenberg.org/ebooks/1342", "Pride and Prejudice"),
        ("https://www.gutenberg.org/ebooks/98", "A Tale of Two Cities"),
    ]

    results = downloader.process_books(
        [book_url for book_url, _ in books],
        format_type="text",
        output_dir="./processed_books"
    )

    print(f"\nProcessed {len(results)} books:\n")
    for i, result in enumerate(results, 1):
        if result['status'] == 'success':
            print(f"{i}. {result['title']}")
            print(f"   File: {result['file']}")

            # Load and display stats
            with open(result['file'], 'r', encoding='utf-8') as f:
                data = json.load(f)
                print(f"   Chapters: {len(data['chapters'])}")
                print(f"   Text length: {len(data['main_text'])} characters")
        else:
            print(f"{i}. FAILED: {result['url']}")
        print()


def example_3_process_and_extract():
    """Example 3: Process a book and extract specific information."""
    print("\n" + "=" * 70)
    print("Example 3: Process and Extract Specific Information")
    print("=" * 70)

    downloader = GutenbergDownloader(cache_dir="./gutenberg_cache")

    # Download Pride and Prejudice
    book_url = "https://www.gutenberg.org/ebooks/1342"
    print(f"\nDownloading: {book_url}")

    content = downloader.download_book(book_url, format_type="text")

    if content:
        book_data = downloader.parse_text_book(content)

        print(f"\nTitle: {book_data['title']}")
        print(f"Format: {book_data['format']}")
        print(f"Source: {book_data['source']}")

        # Extract and display chapters
        print(f"\n--- Chapter Titles ({len(book_data['chapters'])} found) ---")
        for i, chapter in enumerate(book_data['chapters'][:10], 1):
            print(f"{i}. {chapter[:60]}")  # Truncate for display

        # Extract and display statistics
        print(f"\n--- Content Statistics ---")
        print(f"Total characters: {len(book_data['main_text']):,}")
        print(f"Total words (approx): {len(book_data['main_text'].split()):,}")
        print(f"Average chapter length: {len(book_data['main_text']) / len(book_data['chapters']):.0f} characters")

        # Display text sample
        print(f"\n--- Text Sample (first 800 characters) ---")
        print(book_data['main_text'][:800])
        print("...")


def example_4_save_as_text():
    """Example 4: Save extracted book as plain text file."""
    print("\n" + "=" * 70)
    print("Example 4: Save Book as Plain Text File")
    print("=" * 70)

    downloader = GutenbergDownloader(cache_dir="./gutenberg_cache")

    # Download Little Women
    book_url = "https://www.gutenberg.org/ebooks/514"
    print(f"\nDownloading: {book_url}")

    content = downloader.download_book(book_url, format_type="text")

    if content:
        book_data = downloader.parse_text_book(content)

        # Create output file
        output_file = Path("./processed_books/little_women.txt")
        output_file.parent.mkdir(parents=True, exist_ok=True)

        with open(output_file, 'w', encoding='utf-8') as f:
            # Write title
            f.write(f"{'='*70}\n")
            f.write(f"{book_data['title']}\n")
            f.write(f"{'='*70}\n\n")

            # Write chapter list
            if book_data['chapters']:
                f.write("CHAPTERS:\n")
                for chapter in book_data['chapters']:
                    f.write(f"  - {chapter}\n")
                f.write("\n" + "="*70 + "\n\n")

            # Write main text
            f.write(book_data['main_text'])

        print(f"Saved to: {output_file}")
        print(f"File size: {output_file.stat().st_size:,} bytes")


def example_5_extract_first_chapter():
    """Example 5: Extract and save only the first chapter."""
    print("\n" + "=" * 70)
    print("Example 5: Extract and Save First Chapter")
    print("=" * 70)

    downloader = GutenbergDownloader(cache_dir="./gutenberg_cache")

    # Download A Tale of Two Cities
    book_url = "https://www.gutenberg.org/ebooks/98"
    print(f"\nDownloading: {book_url}")

    content = downloader.download_book(book_url, format_type="text")

    if content:
        book_data = downloader.parse_text_book(content)

        print(f"\nTitle: {book_data['title']}")
        print(f"Chapters: {len(book_data['chapters'])}")

        # Find first chapter marker in text
        if book_data['chapters']:
            first_chapter = book_data['chapters'][0]
            print(f"\nFirst chapter: {first_chapter}")

            # Save first chapter metadata
            chapter_data = {
                'book_title': book_data['title'],
                'chapter_title': first_chapter,
                'chapter_number': 1,
                'text_preview': book_data['main_text'][:1000]
            }

            output_file = Path("./processed_books/chapter_extract.json")
            output_file.parent.mkdir(parents=True, exist_ok=True)
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(chapter_data, f, indent=2, ensure_ascii=False)

            print(f"\nSaved chapter data to: {output_file}")


def example_6_api_usage():
    """Example 6: Using the downloader as a Python API."""
    print("\n" + "=" * 70)
    print("Example 6: Python API Usage")
    print("=" * 70)

    # Initialize downloader
    downloader = GutenbergDownloader(cache_dir="./gutenberg_cache")

    # Download a book
    print("\nDownloading book...")
    content = downloader.download_book(
        "https://www.gutenberg.org/ebooks/11",
        format_type="text"
    )

    # Parse the book
    print("Parsing book...")
    book_data = downloader.parse_text_book(content)

    # Access data programmatically
    print(f"\nBook Title: {book_data['title']}")
    print(f"Format: {book_data['format']}")
    print(f"Source: {book_data['source']}")
    print(f"Chapters: {len(book_data['chapters'])}")

    # Use the data in your application
    book_json = json.dumps(book_data, ensure_ascii=False)
    print(f"\nJSON representation size: {len(book_json):,} bytes")


def main():
    """Run all examples."""
    print("\n")
    print("#" * 70)
    print("# Project Gutenberg Downloader - Usage Examples")
    print("#" * 70)

    # Run examples
    try:
        example_1_single_book()
    except Exception as e:
        print(f"Example 1 error: {e}")

    try:
        example_2_multiple_books()
    except Exception as e:
        print(f"Example 2 error: {e}")

    try:
        example_3_process_and_extract()
    except Exception as e:
        print(f"Example 3 error: {e}")

    try:
        example_4_save_as_text()
    except Exception as e:
        print(f"Example 4 error: {e}")

    try:
        example_5_extract_first_chapter()
    except Exception as e:
        print(f"Example 5 error: {e}")

    try:
        example_6_api_usage()
    except Exception as e:
        print(f"Example 6 error: {e}")

    print("\n" + "=" * 70)
    print("All examples completed!")
    print("=" * 70 + "\n")


if __name__ == "__main__":
    main()