-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslack_overflow.py
151 lines (126 loc) · 3.44 KB
/
slack_overflow.py
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
from flask import Flask
import os
import logging
from joblib import dump, load
from flask import request, jsonify, abort
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
import json
from question_tagger import QuestionTagger
import torch
import numpy as np
from transformers import BertTokenizerFast as BertTokenizer, BertModel, AdamW, get_linear_schedule_with_warmup
SLACK_TOKEN = os.environ.get("SLACK_TOKEN")
client = WebClient(token=SLACK_TOKEN)
logger = logging.getLogger(__name__)
app = Flask(__name__)
# model = load("naivebayes.joblib")
BERT_MODEL_NAME = 'bert-base-cased'
bert = QuestionTagger(n_classes=3)
bert.load_state_dict(torch.load("trained_model.pth"))
channel_public_ids = {"python": "C028ZTHBP33", "cloud": "C0286GGP3PH", "node": "C028ZTLBQL9"}
@app.route('/', methods=["POST"])
def action():
try:
payload = json.loads(request.form["payload"])
print(payload)
actions = payload.get("actions")[0]
action_id = actions.get("action_id")
if action_id == "post":
user = payload.get("user").get("username")
value = json.loads(actions["value"])
question = value["question"]
channel_id = value["channel_id"]
text = f"""New question from <@{user}>:
{question}
"""
client.chat_postMessage(
channel=channel_id,
text=text
)
return jsonify({})
elif action_id == "post_anon":
value = json.loads(actions["value"])
question = value["question"]
channel_id = value["channel_id"]
text = question
client.chat_postMessage(
channel=channel_id,
text=text
)
return jsonify({})
except SlackApiError as e:
# print(f"Error: {e}")
raise e
@app.route('/where', methods=['POST'])
def recommend():
# Parse the parameters you need
text = request.form.get('text', None)
if text == None or text == '':
return "Please enter a question."
channel = predict(text)
channel_id = channel_public_ids.get(channel)
val = { "question" : text, "channel_id" : channel_id}
return jsonify({
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*"+text+"*"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":slack: Post your question in <#"+channel_id+"|"+channel+"> :slack:."
}
},
{
"type": "actions",
"block_id": "actionblock789",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "Post Question"
},
"style": "primary",
"value": json.dumps(val),
"action_id": "post"
},
{
"type": "button",
"text": {
"type": "plain_text",
"text": "Post Anonymously"
},
"style": "primary",
"value": json.dumps(val),
"action_id": "post_anon"
}
]
}
]
})
def predict(text):
test_comment = text
tokenizer = BertTokenizer.from_pretrained(BERT_MODEL_NAME)
encoding = tokenizer.encode_plus(
test_comment,
add_special_tokens=True,
max_length=128,
return_token_type_ids=False,
padding="max_length",
return_attention_mask=True,
return_tensors='pt',
)
_, test_prediction = bert(encoding["input_ids"], encoding["attention_mask"])
test_prediction = test_prediction.flatten().detach().numpy()
LABEL_COLUMNS = ['cloud', 'node', 'python']
return LABEL_COLUMNS[np.argmax(test_prediction)]
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=True)