Esempio n. 1
0
def chat(request):
    custs = Customer.objects.all()

    consumer_key = 'q3NopxIzKRa7cXvPGXCInkFee'
    consumer_secret = 'TcvYUi4oIiDOonBO0crCoy4D3UjdjHpY0r8cjSpnZyMl6UP4H8'

    access_token = '1254647674160078848-32NJL0yJcmKx3y9n8eQht0d7pUtzNt'
    access_token_secret = 'zsVUrFkxLqMGABg1VopYqKKEdThb25tNaNXYprPx9ewuh'

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    api = tweepy.API(auth)

    for names in custs:
        polarity = 0
        subjectivity = 0
        name = str(names.name)
        public_tweets = api.search(name)
        print(name)
        for tweet in public_tweets:
            analysis = TextBlob(tweet.text)
            Sentiment = analysis.sentiment
            polarity += Sentiment.polarity
            subjectivity += Sentiment.subjectivity
            names.pol = polarity
            names.sub = subjectivity
            names.save()

    return render(request, 'chat.html', {'custs': custs})
Esempio n. 2
0
def chat(request):
    custs = Customer.objects.all()

    consumer_key = 'midEzHb8nacvmLGo1c2fmita9'
    consumer_secret = 'nEx2a7AU1N31laL82pr9fK2B1jdLgrtQfxWTVt2II4CetapSwz'
    access_token = '1254277768449347586-Wo5FXro68ailMEV4mMiZRIVNRDT9cY'
    access_token_secret = 's2EJVlVO30RKlsJ7jT1hUVOVb3zDOvYhJg9KOxC4kNcx3'

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    api = tweepy.API(auth)

    for names in custs:
        polarity = 0
        subjectivity = 0
        name = str(names.name)
        public_tweets = api.search(name)
        print(name)
        for tweet in public_tweets:
            analysis = TextBlob(tweet.text)
            Sentiment = analysis.sentiment
            polarity += Sentiment.polarity
            subjectivity += Sentiment.subjectivity
            names.pol = polarity
            names.sub = subjectivity
            names.save()

    return render(request, 'chat.html', {'custs': custs})
Esempio n. 3
0
def sentimental(request):
    subjectivity = 0
    polarity = 0
    customers = Customers.objects.all()
    for customer in customers:
        print("inside loop")
        consumer_key = 'I5uJYivxN2sZRuz7JbyqIU0dg'
        consumer_secret = 'tO8kCyFHb0HwPZeq8Vvz2z9eEUc4xSXD56QhmzqrWiDSRbuahz'
        access_token = '1249729070671130624-xme25T1yhnLWHwQM9ECuJIN9u7fJss'
        access_token_secret = 'J67rF7bVEGvBdLEwGBs20Jgl0Nb59JNAakobSiocrTmAP'
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        api = tweepy.API(auth)
        public_tweets = api.search(customer.name)
        print("after search operation")
        for tweet in public_tweets:
            print(tweet.text)
            analysis = TextBlob(tweet.text)
            polarity = polarity + analysis.polarity
            subjectivity = subjectivity + analysis.subjectivity
            print(analysis.sentiment)
            print("analysis is printed above")
        customer.polarity = polarity
        customer.subjectivity = subjectivity
        customer.save()
        print("after save")
    return render(request, 'tweet.html', {'customers': customers})
Esempio n. 4
0
def getTweets():
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    public_tweets = api.home_timeline(count=10)
    tweets = []
    for tweet in public_tweets:
        status = tweet.text
        tweets.append({'status': status})
    return {'tweets': tweets}
Esempio n. 5
0
def postTweet(up_status):
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    api.update_status(up_status)
Esempio n. 6
0
def fakeornot(request):
    auth = tweepy.OAuthHandler(
        "x4yJNIGwJBspKCD3jXps0udJm",
        "Xzi5PvN4rHvqBr6kPgcUCiSRDLLGLFJDFRZ1gPAvXxv5kvhyZZ")
    auth.set_access_token("2491739339-q9jEkfotc22ETdAKFGNWiKLY7NCAtmy5cMbbMXI",
                          "UqdiqHDl1h5czl9jxpgDZQezm9mw88hA3qzX3Q72yHTA1")
    api = tweepy.API(auth)
    names = [
        'twtCount', 'engRatio', 'frndcount', 'biolen', 'likecount', 'verified',
        'default', 'class'
    ]
    ds = pandas.read_csv("static/dataset_original.csv", names=names)
    print("shape: {}".format(ds.shape))
    array = ds.values
    X = array[:, 0:7]
    Y = array[:, 7]
    X_train, X_validation, Y_train, Y_validation = train_test_split(
        X, Y, test_size=0.30, random_state=None)
    print("x shape: {}".format(X_train.shape))
    print("y shape: {}".format(Y_train.shape))
    print("x test shape: {}".format(X_validation.shape))
    print("y test shape: {}".format(Y_validation.shape))
    print("x_train:{}".format(X_train))
    print("X_test:{}".format(X_validation))

    # Spot Check Algorithms
    models = []
    models.append(
        ('LR', LogisticRegression(solver='liblinear', multi_class='ovr')))
    models.append(('LDA', LinearDiscriminantAnalysis()))
    models.append(('KNN', KNeighborsClassifier()))
    models.append(('CART', DecisionTreeClassifier()))
    models.append(('NB', GaussianNB()))
    models.append(('SVM', SVC(gamma='auto')))
    # evaluate each model in turn
    results = []
    names = []
    for name, model in models:
        kfold = StratifiedKFold(n_splits=5, random_state=None)
        cv_results = cross_val_score(model,
                                     X_train,
                                     Y_train,
                                     cv=kfold,
                                     scoring='accuracy')
        results.append(cv_results)
        names.append(name)
        print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std()))
    lda = LinearDiscriminantAnalysis()
    lda.fit(X_train, Y_train)
    p = request.POST['name1']
    user = api.get_user(p)
    tweet = user.status
    endDate = datetime.datetime(2020, 5, 14, 0, 0, 0)
    startDate = datetime.datetime(2020, 5, 8, 0, 0, 0)
    tweets = []
    tmpTweets = api.user_timeline(p)
    for tweet in tmpTweets:
        if (tweet.created_at < endDate and tweet.created_at > endDate):
            tweets.append(tweet.favorite_count)
    while (tmpTweets[-1].created_at > startDate):
        tmpTweets = api.user_timeline(p, max_id=tmpTweets[-1].id)
        for tweet in tmpTweets:
            if tweet.created_at < endDate and tweet.created_at > startDate:
                tweets.append(tweet.favorite_count)

    if (user.verified) == True:
        a = 1
    else:
        a = 0
    if (user.default_profile) == True:
        b = 0
    else:
        b = 1

    if (len(tweets) == 0):
        t = user.status.favorite_count
    else:
        tweets.sort()
        t = tweets[-1]
    X_new = np.array([[
        user.statuses_count, (t / user.followers_count) * 1000,
        user.friends_count,
        len(user.description), user.favourites_count, a, b
    ]])
    prediction = lda.predict(X_new)
    q = prediction
    print(prediction)
    if q == ['not']:
        v = 0
        return render(request, 'not.html', {
            'result': 'This is a genuine twitter account',
            'l': p
        })
    else:
        v = 1

        auth = tweepy.OAuthHandler(
            "x4yJNIGwJBspKCD3jXps0udJm",
            "Xzi5PvN4rHvqBr6kPgcUCiSRDLLGLFJDFRZ1gPAvXxv5kvhyZZ")
        auth.set_access_token(
            "2491739339-q9jEkfotc22ETdAKFGNWiKLY7NCAtmy5cMbbMXI",
            "UqdiqHDl1h5czl9jxpgDZQezm9mw88hA3qzX3Q72yHTA1")
        api = tweepy.API(auth)
        user = api.get_user(p)
        tweet = user.status
        # Loading the data set - training data.
        from sklearn.datasets import fetch_20newsgroups
        twenty_train = fetch_20newsgroups(subset='train', shuffle=True)

        # In[6]:

        # Extracting features from text files

        count_vect = CountVectorizer()
        X_train_counts = count_vect.fit_transform(twenty_train.data)
        X_train_counts.shape

        # In[7]:

        # TF-IDF
        from sklearn.feature_extraction.text import TfidfTransformer
        tfidf_transformer = TfidfTransformer()
        X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
        X_train_tfidf.shape

        # In[15]:

        # Performance of NB Classifier
        import numpy as nv
        from sklearn.pipeline import Pipeline
        twenty_test = fetch_20newsgroups(subset='test', shuffle=True)

        # Training Support Vector Machines - SVM and calculating its performance

        from sklearn.linear_model import SGDClassifier
        text_clf_svm = Pipeline([('vect', CountVectorizer()),
                                 ('tfidf', TfidfTransformer()),
                                 ('clf-svm',
                                  SGDClassifier(loss='hinge',
                                                penalty='l2',
                                                alpha=1e-3,
                                                random_state=42))])

        text_clf_svm = text_clf_svm.fit(twenty_train.data, twenty_train.target)

        input = user.description
        input = [input]
        pr = text_clf_svm.predict(input)
        res = str(pr)[1:-1]
        print("belongs to the category : " +
              twenty_train.target_names[int(res)])
        return render(request, 'not2.html',
                      {'result': twenty_train.target_names[int(res)]})
Esempio n. 7
0
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import BernoulliNB

##<--- setting connection with the twitter API----->##
temp=[]
credentials = {}
credentials['CONSUMER_KEY'] = "YoknJGgd0DYnUe4m7Z4gSDTK3"
credentials['CONSUMER_SECRET'] = "RU83Rq7hg2aKreuzZzAdzvR9QFCQfk0YMauJPRwI5D8GvgOg4g"
credentials['ACCESS_TOKEN'] = "1275391205598277633-dZD2nyYAqQG3Pb1avTIBvhfsQy0Q6G"
credentials['ACCESS_SECRET'] = "JQz2x78eetOPrFYYh8guwuLtsbtADD2f9zcnxYKddNiNo"
with open("twitter_credentials.json", "w") as file:
    json.dump(credentials, file)
    auth = tw.OAuthHandler(credentials['CONSUMER_KEY'], credentials['CONSUMER_SECRET'])
    auth.set_access_token(credentials['ACCESS_TOKEN'], credentials['ACCESS_SECRET'])
    api = tw.API(auth, wait_on_rate_limit=True)
python_tweets = Twython(credentials['CONSUMER_KEY'], credentials['CONSUMER_SECRET'])

list_of_objects=[]
queryrequest=[]
words=[]
length_of_data = -1
stop = stopwords.words('english')
nlp = spacy.load("en_core_web_sm")

#try:
 #   model = joblib.load('randomforest.joblib')
    #vectorizer = joblib.load('vectorizer.joblib')
    #reslt = joblib.load('resutl.joblib')
    #print('resultant was  ', reslt)