0

我正在使用 NLTK 和 Flask 构建一个 Web 应用程序。这只是一个简单的 RESTful 应用程序,我将它部署在 heroku 上,一切顺利。但是,当服务器开始收到更多请求时,我达到了 heroku 的内存限制,即 1.5GB。所以,我猜这是因为nltk.RegexpParser每次请求到来时我都在加载。

这是非常简单的代码。



@app.route('/get_keywords', methods=['POST'])
def get_keywords():
    data_json = json.loads(request.data)
    text = urllib.unquote(data_json["sentence"])
    keywords = KeywordExtraction().extract(text)

    return ','.join(keywords)

这是关键字提取位。


import re
import nltk

nltk.data.path.append('./nltk_data/')

from nltk.corpus import stopwords

class KeywordExtraction:
    def extract(self, text):

        sentences = nltk.sent_tokenize(text)
        sentences = [nltk.word_tokenize(sent) for sent in sentences]
        sentences = [nltk.pos_tag(sent) for sent in sentences]

        grammar = "NP: {}"
        cp = nltk.RegexpParser(grammar)
        tree = cp.parse(sentences[0])

        keywords = [subtree.leaves()[0][0] for subtree in tree.subtrees(filter=lambda t: t.node == 'NP')]
        keywords_without_stopwords = [w for w in keywords if not w in stopwords.words('english')]

        return list(set(keywords_without_stopwords + tags))

我不确定这是我的代码、Flask 还是 NLTK 的问题。我对 Python 很陌生。任何建议将不胜感激。

我通过 blitz.io 对此进行了测试,仅在 250 个请求之后,服务器就炸毁并开始抛出 R15。

4

1 回答 1

1

从缓存东西开始:

# Move these outside of the class declaration or make them class variables

stopwords = set(stopwords.words('english'))
grammar = "NP: {}"
cp = nltk.RegexpParser(grammar)

这也可以加快一点:

from itertools import ifilterfalse

...

keywords_without_stopwords = ifilterfalse(stopwords.__contains__, keywords)

return list(keywords_without_stopwords + set(tags))  # Can you cache `set(tags`)?

我还想看看 Flask-Cache 以尽可能多地记忆和缓存函数和视图。

于 2013-03-02T01:22:09.620 回答