Skip to content

Commit 1d99037

Browse files
committed
added lib/postprocessing.py
1 parent 7f2bf6c commit 1d99037

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

lib/postprocessing.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import re
2+
import fmt.comments
3+
4+
def postprocess(answer, keyword, options, request_options=None):
5+
answer = _answer_add_comments(answer, request_options=request_options)
6+
answer = _answer_filter_by_keyword(answer, keyword, options, request_options=request_options)
7+
return answer
8+
9+
def _answer_add_comments(answer, request_options=None):
10+
11+
if answer['format'] != 'text+code':
12+
return answer
13+
14+
topic = answer['topic']
15+
filetype = 'bash'
16+
if '/' in topic:
17+
filetype = topic.split('/', 1)[0]
18+
if filetype.startswith('q:'):
19+
filetype = filetype[2:]
20+
21+
answer['answer'] = fmt.comments.beautify(
22+
answer['answer'].encode('utf-8'), filetype, request_options)
23+
answer['format'] = 'code'
24+
return answer
25+
26+
def _answer_filter_by_keyword(answer, keyword, options, request_options=None):
27+
answer['answer'] = _filter_by_keyword(answer['answer'], keyword, options)
28+
return answer
29+
30+
def _filter_by_keyword(answer, keyword, options):
31+
32+
def _join_paragraphs(paragraphs):
33+
answer = "\n".join(paragraphs)
34+
return answer
35+
36+
def _split_paragraphs(text):
37+
answer = []
38+
paragraph = ""
39+
for line in text.splitlines():
40+
if line == "":
41+
answer.append(paragraph)
42+
paragraph = ""
43+
else:
44+
paragraph += line+"\n"
45+
answer.append(paragraph)
46+
return answer
47+
48+
def _paragraph_contains(paragraph, keyword, insensitive=False, word_boundaries=True):
49+
"""
50+
Check if `paragraph` contains `keyword`.
51+
Several keywords can be joined together using ~
52+
For example: ~ssh~passphrase
53+
"""
54+
answer = True
55+
56+
if '~' in keyword:
57+
keywords = keyword.split('~')
58+
else:
59+
keywords = [keyword]
60+
61+
for kwrd in keywords:
62+
regex = re.escape(kwrd)
63+
if not word_boundaries:
64+
regex = r"\b%s\b" % kwrd
65+
66+
if insensitive:
67+
answer = answer and bool(re.search(regex, paragraph, re.IGNORECASE))
68+
else:
69+
answer = answer and bool(re.search(regex, paragraph))
70+
71+
return answer
72+
73+
74+
if not keyword:
75+
return answer
76+
77+
search_options = {
78+
'insensitive': 'i' in options,
79+
'word_boundaries': 'b' in options
80+
}
81+
82+
paragraphs = [p for p in _split_paragraphs(answer)
83+
if _paragraph_contains(p, keyword, **search_options)]
84+
if not paragraphs:
85+
return ""
86+
87+
return _join_paragraphs(paragraphs)

0 commit comments

Comments
 (0)