|
1 | 1 | import logging |
2 | 2 | import json |
| 3 | +import string |
| 4 | +import numpy as np |
3 | 5 |
|
4 | 6 | from flask import request, jsonify; |
5 | 7 |
|
6 | 8 | from codeitsuisse import app; |
7 | 9 |
|
8 | 10 | logger = logging.getLogger(__name__) |
| 11 | +alphabet = string.ascii_lowercase # "abcdefghijklmnopqrstuvwxyz" |
| 12 | +wordSet = set(line.strip() for line in open('./codeitsuisse/routes/en.txt')) |
9 | 13 |
|
10 | 14 | @app.route('/bored-scribe', methods=['POST']) |
11 | 15 | def evaluateBoredScribe(): |
12 | 16 | data = request.get_json(); |
13 | | - logging.info("data sent for evaluation {}".format(data)) |
14 | | - logging.info("My result :{}".format(data)) |
| 17 | + # logging.info("data sent for evaluation {}".format(data)) |
| 18 | + for jsonObject in data: |
| 19 | + encryptedText = jsonObject["encryptedText"] |
| 20 | + selectedText = "" |
| 21 | + lowestEntropy = 10000 |
| 22 | + for i in range(0,26): |
| 23 | + decryptedText = unCaesar(encryptedText,i) |
| 24 | + entropy = getEntropy(decryptedText) |
| 25 | + if entropy < lowestEntropy: |
| 26 | + selectedText = decryptedText |
| 27 | + lowestEntropy = entropy |
| 28 | + print(addSpace(selectedText)) |
| 29 | + # logging.info("My result :{}".format(data)) |
15 | 30 | return json.dumps(data); |
16 | 31 |
|
| 32 | +def unCaesar(encrypted_message, key): |
| 33 | + |
| 34 | + decrypted_message = "" |
| 35 | + for c in encrypted_message: |
17 | 36 |
|
| 37 | + if c in alphabet: |
| 38 | + position = alphabet.find(c) |
| 39 | + new_position = (position - key + 26) % 26 |
| 40 | + new_character = alphabet[new_position] |
| 41 | + decrypted_message += new_character |
| 42 | + else: |
| 43 | + decrypted_message += c |
| 44 | + |
| 45 | + return(decrypted_message) |
| 46 | + |
| 47 | +def addSpace(decryptedText): |
| 48 | + output = [] |
| 49 | + while(len(decryptedText) > 0): |
| 50 | + hasWord = False |
| 51 | + for i in range(len(decryptedText), -1, -1): |
| 52 | + splicedWord = decryptedText[0:i] |
| 53 | + if splicedWord in wordSet: |
| 54 | + output.append(splicedWord) |
| 55 | + decryptedText = decryptedText[i:] |
| 56 | + hasWord = True |
| 57 | + if hasWord: |
| 58 | + break |
| 59 | + if hasWord == False: |
| 60 | + output.append(decryptedText) |
| 61 | + decryptedText = "" |
| 62 | + |
| 63 | + return output |
| 64 | + |
| 65 | +def getEntropy(inputString): |
| 66 | + ENGLISH_FREQS = [0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406,0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074] |
| 67 | + |
| 68 | + sumOfEntropy = 0 |
| 69 | + for i in range(len(inputString)): |
| 70 | + ch = inputString[i] |
| 71 | + chInt = ord(ch) |
| 72 | + if chInt >=97 and chInt <= 122: |
| 73 | + sumOfEntropy += np.log(ENGLISH_FREQS[chInt-97]) |
| 74 | + return (sumOfEntropy * -1)/ np.log(2.0)/ len(inputString) |
18 | 75 |
|
0 commit comments