<commit_before>import threading
import requests
from requests_oauthlib import OAuth1Session
import flask
import json
import sign

BASE_RESPONSE = {
    "version": "1",
    "response": {}
}

with open(".scorekeeper_keys") as f:
    keys = json.load(f)

TWITTER_APP_KEY = keys["api_key"]
TWITTER_APP_KEY_SECRET = keys["api_secret"]
TWITTER_ACCESS_TOKEN = keys["access_token"]
TWITTER_ACCESS_TOKEN_SECRET = keys["token_secret"]

twitter = OAuth1Session(
    TWITTER_APP_KEY,
    client_secret=TWITTER_APP_KEY_SECRET,
    resource_owner_key=TWITTER_ACCESS_TOKEN,
    resource_owner_secret=TWITTER_ACCESS_TOKEN_SECRET
)

api = flask.Flask(__name__)

SIGN = sign.Sign("192.168.4.105", 8800)

def get_points():
    points = {}
    try:
        with open('.points') as p:
            points = json.load(p)
    except FileNotFoundError:
        with open('.points', 'w') as p:
            json.dump({}, p)
    return points

def add_point(person):
    points = get_points()
    person = person.lower()
    if person in points:
        points[person] += 1
    else:
        points[person] = 1

    with open('.points', 'w') as p:
        json.dump(points, p)

def points_for(person):
    return get_points().get(person.lower(), 0)

def do_tweet(person, reason):
    if reason:
        if reason.lower().startswith("for "):
            reason = reason[4:]
    r = twitter.post("https://api.twitter.com/1.1/statuses/update.json",
                      data={"status": "Crazy point to {}: {}".format(person.title(), reason)})
    print("Status:", r.text)
    print("Person", person, "\nReason", reason)

def _display_thread():
    texts = ["{}: {}".format(*i) for i in
             sorted(get_points().items(), key=lambda n:n[1], reverse=True)]
    total_lifetime = len(texts) * 2

    for text in texts:
        SIGN.new_message(texts, priority=2, lifetime=total_lifetime)

def do_display():
    threading.Thread(target=_display_thread).start()

@api.route('/', methods=['POST', 'GET'])
def alexa():
    data = flask.request.data
    if data:
        data = json.loads(data.decode('UTF-8'))
    else:
        raise ValueError("Invalid arguments; no data")

    with open('/tmp/alexa_test', 'a+') as f:
        print("Data  : " + json.dumps(data, indent=2, separators=(',', ': ')) + '\n')

    request = data["request"]
    req_type = request["type"]
    session_id = data["session"]["sessionId"]

    attrs = {"person": None, "reason": None}
    attrs.update(data["session"].get("attributes", {}))

    if req_type == "LaunchRequest":
        descs = ["{} has {} point{}".format(k, v, '' if v == 1 else 's') for (k, v) in
                 sorted(get_points().items(), key=lambda n:n[1], reverse=True)]
        pretty_scores = "There are no scores yet."
        if len(descs) == 1:
            pretty_scores = ';'.join(descs)
        elif len(descs) > 1:
            pretty_scores = ';'.join(descs[:-1]) + '; and ' + descs[-1]
        resp = dict(BASE_RESPONSE)
        resp["response"] = {
            "outputSpeech": {
                "type": "PlainText",
                "text": "Here is the Hackafe score breakdown. {}".format(pretty_scores)
            },
            "shouldEndSession": True
        }
        do_display()
        return flask.jsonify(resp)
    elif req_type == "SessionEndedRequest":
        resp = dict(BASE_RESPONSE)
        resp["response"] = {
            "shouldEndSession": True
        }<commit_msg>Don't include people with no points<commit_after>import threading
import requests
from requests_oauthlib import OAuth1Session
import flask
import json
import sign

BASE_RESPONSE = {
    "version": "1",
    "response": {}
}

with open(".scorekeeper_keys") as f:
    keys = json.load(f)

TWITTER_APP_KEY = keys["api_key"]
TWITTER_APP_KEY_SECRET = keys["api_secret"]
TWITTER_ACCESS_TOKEN = keys["access_token"]
TWITTER_ACCESS_TOKEN_SECRET = keys["token_secret"]

twitter = OAuth1Session(
    TWITTER_APP_KEY,
    client_secret=TWITTER_APP_KEY_SECRET,
    resource_owner_key=TWITTER_ACCESS_TOKEN,
    resource_owner_secret=TWITTER_ACCESS_TOKEN_SECRET
)

api = flask.Flask(__name__)

SIGN = sign.Sign("192.168.4.105", 8800)

def get_points():
    points = {}
    try:
        with open('.points') as p:
            points = json.load(p)
    except FileNotFoundError:
        with open('.points', 'w') as p:
            json.dump({}, p)
    return points

def add_point(person):
    points = get_points()
    person = person.lower()
    if person in points:
        points[person] += 1
    else:
        points[person] = 1

    with open('.points', 'w') as p:
        json.dump(points, p)

def points_for(person):
    return get_points().get(person.lower(), 0)

def do_tweet(person, reason):
    if reason:
        if reason.lower().startswith("for "):
            reason = reason[4:]
    r = twitter.post("https://api.twitter.com/1.1/statuses/update.json",
                      data={"status": "Crazy point to {}: {}".format(person.title(), reason)})
    print("Status:", r.text)
    print("Person", person, "\nReason", reason)

def _display_thread():
    texts = ["{}: {}".format(*i) for i in
             sorted(get_points().items(), key=lambda n:n[1], reverse=True)]
    total_lifetime = len(texts) * 2

    for text in texts:
        SIGN.new_message(texts, priority=2, lifetime=total_lifetime)

def do_display():
    threading.Thread(target=_display_thread).start()

@api.route('/', methods=['POST', 'GET'])
def alexa():
    data = flask.request.data
    if data:
        data = json.loads(data.decode('UTF-8'))
    else:
        raise ValueError("Invalid arguments; no data")

    with open('/tmp/alexa_test', 'a+') as f:
        print("Data  : " + json.dumps(data, indent=2, separators=(',', ': ')) + '\n')

    request = data["request"]
    req_type = request["type"]
    session_id = data["session"]["sessionId"]

    attrs = {"person": None, "reason": None}
    attrs.update(data["session"].get("attributes", {}))

    if req_type == "LaunchRequest":
        descs = ["{} has {} point{}".format(k, v, '' if v == 1 else 's') for (k, v) in
                 sorted(get_points().items(), key=lambda n:n[1], reverse=True) if v]
        pretty_scores = "There are no scores yet."
        if len(descs) == 1:
            pretty_scores = ';'.join(descs)
        elif len(descs) > 1:
            pretty_scores = ';'.join(descs[:-1]) + '; and ' + descs[-1]
        resp = dict(BASE_RESPONSE)
        resp["response"] = {
            "outputSpeech": {
                "type": "PlainText",
                "text": "Here is the Hackafe score breakdown. {}".format(pretty_scores)
            },
            "shouldEndSession": True
        }
        do_display()
        return flask.jsonify(resp)
    elif req_type == "SessionEndedRequest":
        resp = dict(BASE_RESPONSE)
        resp["response"] = {
            "shouldEndSession": True
        }
{'fraction_non_alphanumeric': 0.15580819122576883, 'fraction_numerical': 0.009911091677598018, 'mean_word_length': 2.795353982300885, 'pattern_counts': {'":': 24, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1594851', 'n_tokens_mistral': 2333, 'n_tokens_neox': 2258, 'n_words': 491}