feed_importer.py 6.28 KB
Newer Older
Son Dinh's avatar
Son Dinh committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import argparse
import datetime
import json
import logging
import os
import re
import sys

# external
import feedparser
from bs4 import BeautifulSoup
from pelican.utils import slugify
import dateutil

# Constants
SLUG_REGEX_SUBSTITUTIONS = [
    (r'[^\w\s-]', ''),  # remove non-alphabetical/whitespace/'-' chars
    (r'(?u)\A\s*', ''),  # strip leading whitespace
    (r'(?u)\s*\Z', ''),  # strip trailing whitespace
    (r'[-\s]+', '-'),  # reduce multiple whitespace or '-' to single '-'
]

DEFAULT_SOURCES = []

Son Dinh's avatar
Son Dinh committed
25
26
27
28
29
30
31
32
33
IGNORED_TAGS = [
    'security',
    'full',
    'large',
    'medium',
    'thumbnail',
    'uncategorized'
]

Son Dinh's avatar
Son Dinh committed
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

def normalize_str(value, use_unicode=False):
    """
    Normalizes string.

    Took from Django sources.
    """

    import unicodedata
    import unidecode

    REGEX_SUBS = [
        (r'\s+', ' '),  # reduce multiple whitespace
        (r'\s+,', ','),  # remove whitespace before ,
        (r'\s+\.', '.'),  # remove whitespace before .
    ]

    def normalize_unicode(text):
        # normalize text by compatibility composition
        # see: https://en.wikipedia.org/wiki/Unicode_equivalence
        return unicodedata.normalize('NFKC', text)

    # normalization
    value = normalize_unicode(value)

    if not use_unicode:
        # ASCII-fy
        value = unidecode.unidecode(value)

    # perform regex substitutions
    for src, dst in REGEX_SUBS:
        value = re.sub(
            normalize_unicode(src),
            normalize_unicode(dst),
            value,
            flags=re.IGNORECASE)

    return value.strip()


if __name__ == '__main__':
    # arguments
    arg_parser = argparse.ArgumentParser(description='')
    arg_parser.add_argument('--source-file', default='', help='File containing feed sources')
    arg_parser.add_argument('--overwrite', action='store_true', help='Overwrite existing files')
    arg_parser.add_argument('--debug', action='store_true', help='Debug')
    args = arg_parser.parse_args()
    # logger
    logger = logging.getLogger('main')
    logger_handler = logging.StreamHandler()
    logger_formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )
    logger_handler.setFormatter(logger_formatter)
    logger.addHandler(logger_handler)
    if args.debug:
        logger.setLevel(logging.INFO)
    else:
        logger.setLevel(logging.WARNING)
    # load source file
    if args.source_file:
        try:
            sources = json.load(open(args.source_file))
        except Exception as e:
            logger.error(e)
            sys.exit(1)
    else:
        sources = DEFAULT_SOURCES
    # process feed sources
    for source in sources:
        try:
            logger.info(f"Getting feed from URL: {source['url']}")
            d = feedparser.parse(source['url'])
        except Exception as e:
            logger.error(e)
            continue
        # process entries
        for entry in d.entries:
            logger.info(f"Processing link: {entry.link}")
            try:
                if 'published' in entry:
                    dt = dateutil.parser.parse(entry.published)
                else:
                    dt = dateutil.parser.parse(entry.updated)
            except Exception as e:
                logger.error(e)
                continue
Son Dinh's avatar
Son Dinh committed
121
122
123
124
125
            try:
                entry_author = entry.author
            except Exception as e:
                logger.error(e)
                entry_author = source['category']
Son Dinh's avatar
Son Dinh committed
126
127
            # generate output filename
            # TODO: fix when upgrading Pelican to >4.2.0
Son Dinh's avatar
Son Dinh committed
128
129
            entry_slug = slugify(dt.strftime(f'%Y-%m-%d-{entry.title}'), regex_subs=SLUG_REGEX_SUBSTITUTIONS, use_unicode=True)
            # entry_slug = slugify(entry.title, regex_subs=SLUG_REGEX_SUBSTITUTIONS)
Son Dinh's avatar
Son Dinh committed
130
            cwd = os.path.dirname(os.path.realpath(__file__))
Son Dinh's avatar
Son Dinh committed
131
            entry_filename = os.path.join(cwd, dt.strftime(f'content/%Y/%m/{entry_slug}.md'))
Son Dinh's avatar
Son Dinh committed
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
            if not os.path.isdir(os.path.dirname(entry_filename)):
                os.makedirs(os.path.dirname(entry_filename))
            logger.info(f'Filename: {entry_filename}')
            # if file exists but overwrite flag is not set, continue
            if os.path.isfile(entry_filename):
                logger.warning(f'File already exists!: {entry_filename}')
                if not args.overwrite:
                    continue
            # get the correct field for the summary or content
            if isinstance(entry[source['field']], list):
                bs = BeautifulSoup(entry[source['field']][0].value, features="html.parser")
                content = bs.get_text(' ')
                content = normalize_str(content, use_unicode=True).split(' ')
            elif isinstance(entry[source['field']], str):
                bs = BeautifulSoup(entry[source['field']], features="html.parser")
                content = bs.get_text(' ')
                content = normalize_str(content, use_unicode=True).split(' ')
            if content[-1] == '[...]':
                entry_content = ' '.join(content)
            else:
                entry_content = f"{' '.join(content[:100])} [...]"
            # generate tags and categories
            entry_tags = []
            if 'tags' in entry.keys():
                entry_tags = [x.term for x in entry.tags]
            elif 'categories' in entry.keys():
                entry_tags = map(lambda x: x.term, entry.categories)
            if 'tags' in source:
                tags_set = set(source['tags'])
                entry_tags_set = set([x.lower() for x in entry_tags])
                if not entry_tags_set.intersection(tags_set):
                    continue
Son Dinh's avatar
Son Dinh committed
164
            entry_tags = [t for t in entry_tags if t not in IGNORED_TAGS]
Son Dinh's avatar
Son Dinh committed
165
166
167
            # the main content of the Markdown file
            entry = f"""Title: {entry.title}
Date: {dt.isoformat()}
Son Dinh's avatar
Son Dinh committed
168
Author: {entry_author}
Son Dinh's avatar
Son Dinh committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
Category: {source['category']}
Tags: {';'.join(entry_tags)}
Slug: {entry_slug}

[Source]({entry.link}){{:target="_blank" rel="noopener"}}

> {entry_content}
"""
            logger.info(entry)
            # write to the output file
            if os.path.isfile(entry_filename):
                logger.warning(f'Overwriting file: {entry_filename}')
            else:
                logger.warning(f'Writing file: {entry_filename}')
            with open(entry_filename, 'w') as f:
                f.write(entry)
                f.close()