-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
executable file
·66 lines (56 loc) · 1.87 KB
/
main.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
"""`main` is the top level module for your Flask application."""
from __future__ import absolute_import, division, print_function
import logging
from flask import Flask, request, jsonify
import json
import random
import re
from urllib import urlencode
from urllib2 import urlopen
from markovgen import markovgen
app = Flask(__name__)
#DATA_FILE = 'gato_combined.txt'
#DATA_FILE = 'flinch_combined.txt'
DATA_FILE = 'trump_full.txt'
CHAIN_LEN = 3
MIN_WORDS = 5
MAX_WORDS = 12
markov = None
@app.route('/', methods=['GET'])
def index():
global markov
if markov is None:
print("generating...")
markov = markovgen(DATA_FILE, CHAIN_LEN)
num_words = random.randint(MIN_WORDS, MAX_WORDS)
if 'text' in request.args and len(request.args['text'].strip()) > 0:
seed = request.args['text']
else:
seed = None
try:
resp = markov.generate_markov_text(num_words, seed)
resp_dict = {
"response_type": "in_channel",
"text": resp
}
if '/giphy' in resp.lower():
start = resp.lower().find('/giphy') + len('/giphy')
match = re.search('[.!?/]', resp[start:])
if match:
end = start + match.start()
else:
end = None
query = resp[start:end]
search_string = urlencode({'tag': query, 'api_key': 'dc6zaTOxFJmzC'})
try:
giphy = urlopen('http://api.giphy.com/v1/gifs/random?' + search_string)
gif_url = json.load(giphy)['data']['image_url']
resp_dict['attachments'] = [{'image_url': gif_url, 'text': query}]
except Exception as e:
logging.warning(str(e))
except:
resp_dict = {
"response_type": "ephemeral",
"text": "Search term not found."
}
return jsonify(**resp_dict)