logic rewritten
Browse files
app.py
CHANGED
@@ -1,33 +1,56 @@
|
|
1 |
-
from flask import Flask, request
|
2 |
-
from
|
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 |
-
return
|
31 |
-
|
32 |
-
|
33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
+
from nltk import sent_tokenize, word_tokenize, FreqDist
|
3 |
+
from nltk.corpus import stopwords
|
4 |
+
from nltk.tokenize.treebank import TreebankWordDetokenizer
|
5 |
+
import nltk
|
6 |
+
|
7 |
+
app = Flask(__name__)
|
8 |
+
|
9 |
+
nltk.download("punkt")
|
10 |
+
nltk.download("stopwords")
|
11 |
+
|
12 |
+
stop_words = set(stopwords.words("english"))
|
13 |
+
|
14 |
+
def summarize_text(text):
|
15 |
+
sentences = sent_tokenize(text)
|
16 |
+
words = word_tokenize(text)
|
17 |
+
|
18 |
+
# Remove stopwords
|
19 |
+
words = [word.lower() for word in words if word.isalnum() and word.lower() not in stop_words]
|
20 |
+
|
21 |
+
# Calculate word frequency
|
22 |
+
freq_dist = FreqDist(words)
|
23 |
+
|
24 |
+
# Sort sentences based on the sum of word frequencies
|
25 |
+
sorted_sentences = sorted(sentences, key=lambda sentence: sum(freq_dist[word] for word in word_tokenize(sentence)))
|
26 |
+
|
27 |
+
# Take the top 3 sentences as the summary
|
28 |
+
summary = " ".join(sorted_sentences[-3:])
|
29 |
+
|
30 |
+
return summary
|
31 |
+
|
32 |
+
def extract_keywords(text):
|
33 |
+
words = word_tokenize(text)
|
34 |
+
keywords = [word.lower() for word in words if word.isalnum() and word.lower() not in stop_words]
|
35 |
+
return keywords
|
36 |
+
|
37 |
+
@app.route('/text/summarize', methods=['POST'])
|
38 |
+
def summarize_text_route():
|
39 |
+
data = request.get_json()
|
40 |
+
text = data['text']
|
41 |
+
|
42 |
+
summary = summarize_text(text)
|
43 |
+
|
44 |
+
return jsonify({'summary': summary})
|
45 |
+
|
46 |
+
@app.route('/text/extract', methods=['POST'])
|
47 |
+
def extract_keywords_route():
|
48 |
+
data = request.get_json()
|
49 |
+
text = data['text']
|
50 |
+
|
51 |
+
keywords = extract_keywords(text)
|
52 |
+
|
53 |
+
return jsonify({'keywords': keywords})
|
54 |
+
|
55 |
+
if __name__ == '__main__':
|
56 |
+
app.run(debug=True)
|