Exemplo n.º 1
0
    def __init__(self, path):
        """
        Instantiates an instance of the LogParser
        :param str username: Service Credential username
        :param str password: Service Credential password
        """
        with open('./' + path, 'r') as f:
            initparser = configparser.ConfigParser()
            initparser.read_file(f)
            initparser.keys()

        self.personality_client = PersonalityInsightsV2(
            username=initparser['p']['username'],
            password=initparser['p']['password'])
        self.tone_client = ToneAnalyzerV3(
            username=initparser['tone']['username'],
            password=initparser['tone']['password'],
            version="2016-02-11")
        self.decision_client = TradeoffAnalyticsV1(
            username=initparser['decision']['username'],
            password=initparser['decision']['password'])

        self.logs = []
        self.lenlog = [len(self.logs)]
        self.axes = defaultdict(lambda: [0] * (len(self.lenlog) - 1))
        self.axes['x'] = self.lenlog
    def analyse(username):
        statuses = api.GetUserTimeline(screen_name=username, count=200, include_rts=False)
        text = ""
        for s in statuses:
            if (s.lang == 'en'):
                text += s.text

        user_personality = PersonalityInsightsV2(username=USERNAME, password=PASSWORD).profile(text)

        return user_personality
Exemplo n.º 3
0
import json
from os.path import join, dirname
from watson_developer_cloud import PersonalityInsightsV2


personality_insights = PersonalityInsightsV2(
    username='******',
    password='******')

with open(join(dirname(__file__), '../resources/personality.txt')) as \
        personality_text:
    print(json.dumps(personality_insights.profile(
        text=personality_text.read()), indent=2))

# with open(join(dirname(__file__), '../resources/personality.txt')) as \
#         personality_text:
#     personality_insights_json = {"contentItems": [
#         {"id": "245160944223793152", "userid": "bob", "sourceid": "twitter",
#          "created": 1427720427, "updated": 1427720427,
#          "contenttype": "text/plain", "charset": "UTF-8",
#          "language": "en-us", "content": personality_text.read(),
#          "parentid": "", "reply": "false", "forward": "false"}]}
# print(json.dumps(personality_insights.profile(
#     text=personality_insights_json), indent=2))
#
# with open(join(dirname(__file__), '../resources/personality.es.txt')) as \
#         personality_text:
#     print(json.dumps(personality_insights.profile(
#         text=personality_text.read(), language='es'), indent=2))
Exemplo n.º 4
0
import json
from os.path import join, dirname
from watson_developer_cloud import PersonalityInsightsV2

#{
#  "url": "https://gateway.watsonplatform.net/personality-insights/api",
#  "username": "******",
#  "password": "******"
#}

personality_insights = PersonalityInsightsV2(
    username='******', password='******')

with open(join(dirname(__file__), '../resources/personality.txt')) as \
         personality_text:
    personality_insights_json = {
        "contentItems": [{
            "id": "245160944223793152",
            "userid": "bob",
            "sourceid": "twitter",
            "created": 1427720427,
            "updated": 1427720427,
            "contenttype": "text/plain",
            "charset": "UTF-8",
            "language": "en-us",
            "content": personality_text.read(),
            "parentid": "",
            "reply": "false",
            "forward": "false"
        }]
    }
Exemplo n.º 5
0
import json
from os.path import join, dirname
from watson_developer_cloud import PersonalityInsightsV2

personality_insights = PersonalityInsightsV2(username='******',
                                             password='******')

with open(join(dirname(__file__), './resources/personality.txt')) as \
        personality_text:
    print(
        json.dumps(personality_insights.profile(text=personality_text.read()),
                   indent=2))
Exemplo n.º 6
0
import json
from os.path import join, dirname
from watson_developer_cloud import PersonalityInsightsV2


personality_insights = PersonalityInsightsV2(
    username='******',
    password='******')

with open(join(dirname(__file__), '../scripts/freeresponse.txt')) as personality_text:
	json_object=personality_insights.profile(text=personality_text.read(), language='es')
#	print(json.dumps(personality_insights.profile(text=personality_text.read(), language='es'), indent=2))

print('Extraversion: '+str(json_object['tree']['children'][0]['children'][0]['percentage']*100)+'%')
print('Agreeableness: '+str(json_object['tree']['children'][0]['children'][0]['children'][3]['percentage']*100)+'%')
print('Contientousness: '+str(json_object['tree']['children'][0]['children'][0]['children'][1]['percentage']*100)+'%')
print('Neuroticism: '+str(json_object['tree']['children'][0]['children'][0]['children'][4]['percentage']*100)+'%')
print('Openness: '+str(json_object['tree']['children'][0]['children'][0]['children'][0]['percentage']*100)+'%')
Exemplo n.º 7
0
	service = discovery.build('commentanalyzer', 'v1alpha1', developerKey=API_KEY)

	analyze_request = {
		'comment': { 'text': str },
		'requestedAttributes': {'TOXICITY': {}}
		}
	try:
		response = service.comments().analyze(body=analyze_request).execute()
		json.dumps(response)
		# print response.attributeScores.TOXICITY.summaryScore.value
		return response["attributeScores"]["TOXICITY"]["summaryScore"]["value"]
	
	except googleapiclient.errors.HttpError as e:
		return "Error!"	

personality_insights = PersonalityInsightsV2( username='******',password='******')

def userPerspectiveScore(user):
	print(user)
	perspectiveScore = 0
	for comment in reddit.redditor(str(user)).comments.new(limit=10000):
		try:
			strUser += comment.body
		except:
			print ("Errorstr")
		try:
			perspectiveScore += float(runPerspective(strUser))
		except:
			print ("Error")
	
	try:
Exemplo n.º 8
0
def post_list(request):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')

    language_translator = LanguageTranslator(
        username='******',
        password='******')

    personality_insights = PersonalityInsightsV2(
        username='******',
        password='******')

    # print(json.dumps(translation, indent=2, ensure_ascii=False))

    for post in posts:
        posting = post.text
        toneObj = json.dumps(tone_analyzer.tone(tone_input=posting,
                                                content_type="text/plain"),
                             indent=2)
        post.toneObj2 = json.loads(toneObj)
        post.angerScore = post.toneObj2['document_tone']['tone_categories'][0][
            'tones'][0]['score']
        post.disgustScore = post.toneObj2['document_tone']['tone_categories'][
            0]['tones'][1]['score']
        post.fearScore = post.toneObj2['document_tone']['tone_categories'][0][
            'tones'][2]['score']
        post.joyScore = post.toneObj2['document_tone']['tone_categories'][0][
            'tones'][3]['score']
        post.sadScore = post.toneObj2['document_tone']['tone_categories'][0][
            'tones'][4]['score']

        translation = language_translator.translate(text=post.text,
                                                    source='en',
                                                    target='de')
        obj = json.dumps(translation, indent=2, ensure_ascii=False)
        post.obj2 = json.loads(obj)
        post.translate_spanish = post.obj2['translations'][0][
            'translation']  #[0]['word_count'][0]['character_count']
        post.wordcount = post.obj2['word_count']
        post.charactercount = post.obj2['character_count']

        ## personality insights for extra credit

        profile = personality_insights.profile(text=post.text,
                                               content_type="text/plain",
                                               language='en')
        personObj = json.dumps(profile, indent=4, ensure_ascii=False)
        post.obj3 = json.loads(personObj)

        post.openness = post.obj3['tree']['children'][0]['children'][0][
            'children'][0]['percentage']
        post.conscientiousness = post.obj3['tree']['children'][0]['children'][
            0]['children'][1]['percentage']
        post.extraversion = post.obj3['tree']['children'][0]['children'][0][
            'children'][2]['percentage']
        post.agreeableness = post.obj3['tree']['children'][0]['children'][0][
            'children'][3]['percentage']

        post.personlity = post.obj3['tree']['children'][0]['children'][0][
            'children']
        post.pstring = ""
        for value in post.personlity:
            if value['percentage'] >= 0.5:
                name = value['name']
                percentage = str(value['percentage'])
                # post.needslist.append({'name': name, 'percentage': percentage})
                post.pstring += (name + " : " + percentage + " | ")

        for value in post.personlity:
            # if value['percentage'] >= 0.5:
            #     name = value['name']
            #     percentage = str(value['percentage'])
            #     # post.needslist.append({'name': name, 'percentage': percentage})
            #     post.pstring += (name + " : " + percentage + " | ")

            person = value['children']
            for i in person:
                if i['percentage'] >= 0.5:
                    name1 = i['name']
                    percentage1 = str(i['percentage'])
                    # post.needslist.append({'name': name, 'percentage': percentage})
                    post.pstring += (name1 + " : " + percentage1 + " | ")

        post.needs = post.obj3['tree']['children'][1]['children'][0][
            'children']
        # post.needslist = []
        post.needstring = ""
        for value in post.needs:
            if value['percentage'] >= 0.5:
                name = value['name']
                percentage = str(value['percentage'])
                # post.needslist.append({'name': name, 'percentage': percentage})
                post.needstring += (name + " : " + percentage + " | ")

        post.values = post.obj3['tree']['children'][2]['children'][0][
            'children']
        # post.valuelist = []
        post.valuestring = ""
        for value in post.values:
            if value['percentage'] >= 0.5:
                name = value['name']
                percentage = str(value['percentage'])
                # post.valuelist.append({'name':name,'percentage':percentage})
                post.valuestring += (name + " : " + percentage + " | ")

        # post.obj4 = post.obj3['tree']['children']
        #
        # for i in post.obj4:
        #     obj5 = post.obj4[i]['children']

    return render(request, 'blog/post_list.html', {'posts': posts})
Exemplo n.º 9
0
    def facet_calculation(self, tweets):
        from watson_developer_cloud import PersonalityInsightsV2

        personality_insights = PersonalityInsightsV2(
            username='******',
            password='******')

        obj = (personality_insights.profile(text=tweets))
        # openness
        # adventerous = obj['tree']['children'][0]['children'][0]['children'][0]['children'][0]['percentage']
        # artistic = obj['tree']['children'][0]['children'][0]['children'][0]['children'][1]['percentage']
        emotionality = obj['tree']['children'][0]['children'][0]['children'][
            0]['children'][2]['percentage']
        # imagination = obj['tree']['children'][0]['children'][0]['children'][0]['children'][3]['percentage']
        intellect = obj['tree']['children'][0]['children'][0]['children'][0][
            'children'][4]['percentage']
        liberalism = obj['tree']['children'][0]['children'][0]['children'][0][
            'children'][5]['percentage']
        opennessList = [emotionality, intellect, liberalism]

        # Conscientiousness
        # achievement_striving = obj['tree']['children'][0]['children'][0]['children'][1]['children'][0]['percentage']
        # cautiousness = obj['tree']['children'][0]['children'][0]['children'][1]['children'][1]['percentage']
        dutifulness = obj['tree']['children'][0]['children'][0]['children'][1][
            'children'][2]['percentage']
        orderliness = obj['tree']['children'][0]['children'][0]['children'][1][
            'children'][3]['percentage']
        self_discipline = obj['tree']['children'][0]['children'][0][
            'children'][1]['children'][4]['percentage']
        # self_efficacy = obj['tree']['children'][0]['children'][0]['children'][1]['children'][5]['percentage']
        conscienList = [dutifulness, orderliness, self_discipline]

        # Extraversion
        # activity_level = obj['tree']['children'][0]['children'][0]['children'][2]['children'][0]['percentage']
        # assertiveness = obj['tree']['children'][0]['children'][0]['children'][2]['children'][1]['percentage']
        # cheerfulness = obj['tree']['children'][0]['children'][0]['children'][2]['children'][2]['percentage']
        excitement_seeking = obj['tree']['children'][0]['children'][0][
            'children'][2]['children'][3]['percentage']
        friendliness = obj['tree']['children'][0]['children'][0]['children'][
            2]['children'][4]['percentage']
        gregariousness = obj['tree']['children'][0]['children'][0]['children'][
            2]['children'][5]['percentage']
        extraversionList = [excitement_seeking, friendliness, gregariousness]

        # Agreeableness
        # altruism = obj['tree']['children'][0]['children'][0]['children'][3]['children'][0]['percentage']
        cooperation = obj['tree']['children'][0]['children'][0]['children'][3][
            'children'][1]['percentage']
        # modesty = obj['tree']['children'][0]['children'][0]['children'][3]['children'][2]['percentage']
        morality = obj['tree']['children'][0]['children'][0]['children'][3][
            'children'][3]['percentage']
        # sympathy = obj['tree']['children'][0]['children'][0]['children'][3]['children'][4]['percentage']
        trust = obj['tree']['children'][0]['children'][0]['children'][3][
            'children'][5]['percentage']
        agreeList = [cooperation, morality, trust]

        # Emotional Range
        anger = obj['tree']['children'][0]['children'][0]['children'][4][
            'children'][0]['percentage']
        # anxiety = obj['tree']['children'][0]['children'][0]['children'][4]['children'][1]['percentage']
        depression = obj['tree']['children'][0]['children'][0]['children'][4][
            'children'][2]['percentage']
        # immoderation = obj['tree']['children'][0]['children'][0]['children'][4]['children'][3]['percentage']
        # self_consciousness = obj['tree']['children'][0]['children'][0]['children'][4]['children'][4]['percentage']
        vulnerability = obj['tree']['children'][0]['children'][0]['children'][
            4]['children'][5]['percentage']
        emotionList = [anger, depression, vulnerability]

        facetList = [
            opennessList, conscienList, extraversionList, agreeList,
            emotionList
        ]
        return facetList
Exemplo n.º 10
0
from flask import Flask, render_template, request, url_for
from flask_cors import CORS, cross_origin
import json
import numpy as np
from urllib2 import Request, urlopen, URLError
from watson_developer_cloud import PersonalityInsightsV2
try:
    from SimpleHTTPServer import SimpleHTTPRequestHandler as Handler
    from SocketServer import TCPServer as Server
except ImportError:
    from http.server import SimpleHTTPRequestHandler as Handler
    from http.server import HTTPServer as Server

app = Flask(__name__)
CORS(app, resources=r'/*')
personality_insights = PersonalityInsightsV2(
    username='******', password='******')


def destination(source, priors, dest_list, artistic):
    data = np.full((10, 5), 0.0)
    city_list = {}
    cities = []
    fin1 = open('dataset.txt', 'r')
    i = 0
    for line in fin1:
        cols = line.split()
        city_list[i] = str(cols[0])
        cities.append(cols[0])
        j = 1
        for k in range(5):
            data[i][k] = cols[j]