Created
November 28, 2014 22:09
-
-
Save kunal732/ee828a91dbb57053f1d4 to your computer and use it in GitHub Desktop.
Natural Language Processing on Email
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from flask import Flask, request | |
| from alchemyapi import AlchemyAPI | |
| import sendgrid | |
| import json | |
| app = Flask(__name__) | |
| sg = sendgrid.SendGridClient('username', 'password') | |
| alchemyapi = AlchemyAPI() | |
| def analyze(text): | |
| #this function gets text from email, runs the alchemy api and sends that data back | |
| prebody = "############## Alchemy API analysis of email ##############<br><br>" | |
| response = alchemyapi.combined('text', text) | |
| prebody = prebody + "## Keywords ##<br>" | |
| for keyword in response['keywords']: | |
| prebody = prebody + keyword['text'] + ' : ' + keyword['relevance'] +'<br>' | |
| prebody = prebody + '<br><br>' | |
| prebody = prebody +"## Concepts ##<br>" | |
| for concept in response['concepts']: | |
| prebody = prebody + concept['text'] +' : ' + concept['relevance'] +'<br>' | |
| prebody = prebody + '<br><br>' | |
| prebody = prebody + "## Entities ##<br>" | |
| for entity in response['entities']: | |
| prebody = prebody + entity['type'] + ' : ' + entity['text'] + ' : ' + entity['relevance'] +'<br>' | |
| prebody = prebody + '<br><br>' | |
| prebody = prebody + "############## End of Analysis ##############<br><br>" | |
| return prebody | |
| @app.route('/incoming',methods=['POST']) | |
| def besmart(): | |
| email = request.form['from'] | |
| subject = request.form['subject'] | |
| incoming_body = request.form['text'] | |
| html_body = request.form['html'] | |
| send_from = request.form['to'] | |
| #Get the analysis of the body | |
| prebody = analyze(incoming_body) | |
| if html_body != "": | |
| body = prebody + html_body | |
| else: | |
| body = prebody + incoming_body | |
| new_sub = "Re: "+subject | |
| #Send back that return email | |
| message = sendgrid.Mail() | |
| message.add_to(email) | |
| message.set_subject(new_sub) | |
| message.set_html(body) | |
| message.set_text(body) | |
| message.set_from(send_from) | |
| status, msg = sg.send(message) | |
| return "OK" | |
| if __name__ == '__main__': | |
| app.run(debug = True) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment