Ejemplo n.º 1
0
def new_comment(post_id):
    try:
        loginmodalshow='close'
        loginform = LoginForm()
        if(loginform.validate_on_submit()==False and loginform.login.data):
            loginmodalshow='loginformmodal'
        if loginform.validate_on_submit() and loginform.login.data:
            remember=loginform.remember.data
            email=loginform.email.data
            password=loginform.password.data
            return redirect(url_for('users.login', remember=remember, email=email, password=password))
        modalshow='close'
        registerform = RegistrationForm()
        if(registerform.validate_on_submit()==False and registerform.signup.data):
            modalshow='registerformmodal'
        if registerform.validate_on_submit() and registerform.signup.data:
            username=registerform.username.data
            email=registerform.email.data
            password=registerform.password.data
            return redirect(url_for('users.register', username=username, email=email, password=password))
        form = CommentForm()
        if form.validate_on_submit():
        	post = Post.query.get_or_404(post_id)
        	comment = Comment(content=form.content.data, post=post, comment_author=current_user)
        	db.session.add(comment)
        	db.session.commit()
        	flash('Your comment has been added!', 'success')
        	return redirect(url_for('main.home'))
        return render_template('create_comment.html', title='New Comment', form=form, Legend='New Comment', registerform=registerform, modalshow=modalshow, loginform=loginform, loginmodalshow=loginmodalshow)
    except:
        flash('Something went Wrong. Please check whether enterd details are correct','warning')
        return redirect(url_for('main.forum'))
Ejemplo n.º 2
0
def error_500(error):
    loginmodalshow = 'close'
    loginform = LoginForm()
    if (loginform.validate_on_submit() == False and loginform.login.data):
        loginmodalshow = 'loginformmodal'
    if loginform.validate_on_submit() and loginform.login.data:
        remember = loginform.remember.data
        email = loginform.email.data
        password = loginform.password.data
        return redirect(
            url_for('users.login',
                    remember=remember,
                    email=email,
                    password=password))
    modalshow = 'close'
    registerform = RegistrationForm()
    if (registerform.validate_on_submit() == False
            and registerform.signup.data):
        modalshow = 'registerformmodal'
    if registerform.validate_on_submit() and registerform.signup.data:
        username = registerform.username.data
        email = registerform.email.data
        password = registerform.password.data
        return redirect(
            url_for('users.register',
                    username=username,
                    email=email,
                    password=password))
    return render_template('errors/500.html',
                           registerform=registerform,
                           modalshow=modalshow,
                           loginform=loginform,
                           loginmodalshow=loginmodalshow), 500
Ejemplo n.º 3
0
def comment(comment_id):
    try:
        loginmodalshow='close'
        loginform = LoginForm()
        if(loginform.validate_on_submit()==False and loginform.login.data):
            loginmodalshow='loginformmodal'
        if loginform.validate_on_submit() and loginform.login.data:
            remember=loginform.remember.data
            email=loginform.email.data
            password=loginform.password.data
            return redirect(url_for('users.login', remember=remember, email=email, password=password))
        modalshow='close'
        registerform = RegistrationForm()
        if(registerform.validate_on_submit()==False and registerform.signup.data):
            modalshow='registerformmodal'
        if registerform.validate_on_submit() and registerform.signup.data:
            username=registerform.username.data
            email=registerform.email.data
            password=registerform.password.data
            return redirect(url_for('users.register', username=username, email=email, password=password))
        comment = Comment.query.get_or_404(comment_id)
        return render_template('comment.html', comment_author=comment.comment_author, comment=comment, registerform=registerform, modalshow=modalshow, loginform=loginform, loginmodalshow=loginmodalshow)
    except:
        flash('Something went Wrong. Please check whether enterd details are correct','warning')
        return redirect(url_for('main.forum'))
Ejemplo n.º 4
0
def account():
    try:
        loginmodalshow = 'close'
        loginform = LoginForm()
        if (loginform.validate_on_submit() == False and loginform.login.data):
            loginmodalshow = 'loginformmodal'
        if loginform.validate_on_submit() and loginform.login.data:
            remember = loginform.remember.data
            email = loginform.email.data
            password = loginform.password.data
            return redirect(
                url_for('users.login',
                        remember=remember,
                        email=email,
                        password=password))
        modalshow = 'close'
        registerform = RegistrationForm()
        if (registerform.validate_on_submit() == False
                and registerform.signup.data):
            modalshow = 'registerformmodal'
        if registerform.validate_on_submit() and registerform.signup.data:
            username = registerform.username.data
            email = registerform.email.data
            password = registerform.password.data
            return redirect(
                url_for('users.register',
                        username=username,
                        email=email,
                        password=password))
        form = UpdateAccountForm()
        if form.validate_on_submit():
            if form.picture.data:
                picture_file = save_picture(form.picture.data)
                current_user.image_file = picture_file
            current_user.username = form.username.data
            current_user.email = form.email.data
            db.session.commit()
            flash('Your account has been updated!', 'success')
            return redirect(url_for('users.account'))
        elif request.method == 'GET':
            form.username.data = current_user.username
            form.email.data = current_user.email
        image_file = url_for('static',
                             filename='profile_pics/' +
                             current_user.image_file)
        return render_template('account.html',
                               title='Account',
                               image_file=image_file,
                               form=form,
                               registerform=registerform,
                               modalshow=modalshow,
                               loginform=loginform,
                               loginmodalshow=loginmodalshow)
    except:
        flash(
            'Something went Wrong. Please check whether enterd details are correct',
            'warning')
        return redirect(url_for('main.home'))
Ejemplo n.º 5
0
def reset_token(token):
    try:
        loginmodalshow = 'close'
        loginform = LoginForm()
        if (loginform.validate_on_submit() == False and loginform.login.data):
            loginmodalshow = 'loginformmodal'
        if loginform.validate_on_submit() and loginform.login.data:
            remember = loginform.remember.data
            email = loginform.email.data
            password = loginform.password.data
            return redirect(
                url_for('users.login',
                        remember=remember,
                        email=email,
                        password=password))
        modalshow = 'close'
        registerform = RegistrationForm()
        if (registerform.validate_on_submit() == False
                and registerform.signup.data):
            modalshow = 'registerformmodal'
        if registerform.validate_on_submit() and registerform.signup.data:
            username = registerform.username.data
            email = registerform.email.data
            password = registerform.password.data
            return redirect(
                url_for('users.register',
                        username=username,
                        email=email,
                        password=password))
        if current_user.is_authenticated:
            return redirect(url_for('main.home'))
        user = User.verify_reset_token(token)
        if user is None:
            flash('That is an invalid or expired token', 'warning')
            return redirect(url_for('users.reset_request'))
        form = ResetPasswordForm()
        if form.validate_on_submit():
            hashed_password = bcrypt.generate_password_hash(
                form.password.data).decode('utf-8')
            user.password = hashed_password
            db.session.commit()
            flash('Your password has been updated! You are now able to log in',
                  'success')
            return redirect(url_for('main.home'))
        return render_template('reset_token.html',
                               title='Reset Password',
                               form=form,
                               registerform=registerform,
                               modalshow=modalshow,
                               loginform=loginform,
                               loginmodalshow=loginmodalshow)
    except:
        flash(
            'Something went Wrong. Please check whether enterd details are correct',
            'warning')
        return redirect(url_for('main.home'))
Ejemplo n.º 6
0
def update_post(post_id):
    try:
        loginmodalshow = 'close'
        loginform = LoginForm()
        if (loginform.validate_on_submit() == False and loginform.login.data):
            loginmodalshow = 'loginformmodal'
        if loginform.validate_on_submit() and loginform.login.data:
            remember = loginform.remember.data
            email = loginform.email.data
            password = loginform.password.data
            return redirect(
                url_for('users.login',
                        remember=remember,
                        email=email,
                        password=password))
        modalshow = 'close'
        registerform = RegistrationForm()
        if (registerform.validate_on_submit() == False
                and registerform.signup.data):
            modalshow = 'registerformmodal'
        if registerform.validate_on_submit() and registerform.signup.data:
            username = registerform.username.data
            email = registerform.email.data
            password = registerform.password.data
            return redirect(
                url_for('users.register',
                        username=username,
                        email=email,
                        password=password))
        post = Post.query.get_or_404(post_id)
        if post.author != current_user:
            abort(403)
        form = PostForm()
        if form.validate_on_submit():
            post.title = form.title.data
            post.content = form.content.data
            db.session.commit()
            flash('Your post has been updated!', 'success')
            return redirect(url_for('posts.post', post_id=post.id))
        elif request.method == 'GET':
            form.title.data = post.title
            form.content.data = post.content
        return render_template('create_post.html',
                               title='Update Post',
                               form=form,
                               legend='Update Post',
                               registerform=registerform,
                               modalshow=modalshow,
                               loginform=loginform,
                               loginmodalshow=loginmodalshow)
    except:
        flash(
            'Something went Wrong. Please check whether enterd details are correct',
            'warning')
        return redirect(url_for('main.forum'))
Ejemplo n.º 7
0
def forum():
    try:
        loginmodalshow = 'close'
        loginform = LoginForm()
        if (loginform.validate_on_submit() == False and loginform.login.data):
            loginmodalshow = 'loginformmodal'
        if loginform.validate_on_submit() and loginform.login.data:
            remember = loginform.remember.data
            email = loginform.email.data
            password = loginform.password.data
            return redirect(
                url_for('users.login',
                        remember=remember,
                        email=email,
                        password=password))
        modalshow = 'close'
        registerform = RegistrationForm()
        if (registerform.validate_on_submit() == False
                and registerform.signup.data):
            modalshow = 'registerformmodal'
        if registerform.validate_on_submit() and registerform.signup.data:
            username = registerform.username.data
            email = registerform.email.data
            password = registerform.password.data
            return redirect(
                url_for('users.register',
                        username=username,
                        email=email,
                        password=password))
        form = PostForm()
        if form.validate_on_submit():
            return redirect(
                url_for('posts.new_post',
                        title=form.title.data,
                        content=form.content.data))
        page = request.args.get('page', 1, type=int)
        posts = Post.query.order_by(Post.date_posted.desc()).paginate(
            page=page, per_page=5)
        return render_template('forum.html',
                               posts=posts,
                               form=form,
                               registerform=registerform,
                               modalshow=modalshow,
                               loginform=loginform,
                               loginmodalshow=loginmodalshow)
    except:
        flash(
            'Something went Wrong. Please check weather enterd details are correct',
            'warning')
        return redirect(url_for('main.home'))
Ejemplo n.º 8
0
def reset_request():
    #try:
    loginmodalshow = 'close'
    loginform = LoginForm()
    if (loginform.validate_on_submit() == False and loginform.login.data):
        loginmodalshow = 'loginformmodal'
    if loginform.validate_on_submit() and loginform.login.data:
        remember = loginform.remember.data
        email = loginform.email.data
        password = loginform.password.data
        return redirect(
            url_for('users.login',
                    remember=remember,
                    email=email,
                    password=password))
    modalshow = 'close'
    registerform = RegistrationForm()
    if (registerform.validate_on_submit() == False
            and registerform.signup.data):
        modalshow = 'registerformmodal'
    if registerform.validate_on_submit() and registerform.signup.data:
        username = registerform.username.data
        email = registerform.email.data
        password = registerform.password.data
        return redirect(
            url_for('users.register',
                    username=username,
                    email=email,
                    password=password))
    if current_user.is_authenticated:
        return redirect(url_for('main.home'))
    form = RequestResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        send_reset_email(user)
        flash(
            'An email has been sent with instructions to reset your password.',
            'info')
        return redirect(url_for('main.home'))
    return render_template('reset_request.html',
                           title='Reset Password',
                           form=form,
                           registerform=registerform,
                           modalshow=modalshow,
                           loginform=loginform,
                           loginmodalshow=loginmodalshow)
Ejemplo n.º 9
0
def stack_overflow():
    try:
        loginmodalshow = 'close'
        loginform = LoginForm()
        if (loginform.validate_on_submit() == False and loginform.login.data):
            loginmodalshow = 'loginformmodal'
        if loginform.validate_on_submit() and loginform.login.data:
            remember = loginform.remember.data
            email = loginform.email.data
            password = loginform.password.data
            return redirect(
                url_for('users.login',
                        remember=remember,
                        email=email,
                        password=password))
        modalshow = 'close'
        registerform = RegistrationForm()
        if (registerform.validate_on_submit() == False
                and registerform.signup.data):
            modalshow = 'registerformmodal'
        if registerform.validate_on_submit() and registerform.signup.data:
            username = registerform.username.data
            email = registerform.email.data
            password = registerform.password.data
            return redirect(
                url_for('users.register',
                        username=username,
                        email=email,
                        password=password))
        return render_template('stack_overflow.html',
                               title='Stack Overflow',
                               registerform=registerform,
                               modalshow=modalshow,
                               loginform=loginform,
                               loginmodalshow=loginmodalshow)
    except:
        flash(
            'Something went Wrong. Please check weather enterd details are correct',
            'warning')
        return redirect(url_for('main.home'))
Ejemplo n.º 10
0
def user_comments(username):
    try:
        loginmodalshow = 'close'
        loginform = LoginForm()
        if (loginform.validate_on_submit() == False and loginform.login.data):
            loginmodalshow = 'loginformmodal'
        modalshow = 'close'
        registerform = RegistrationForm()
        if (registerform.validate_on_submit() == False
                and registerform.signup.data):
            modalshow = 'show'
        if registerform.validate_on_submit() and registerform.signup.data:
            username = registerform.username.data
            email = registerform.email.data
            password = registerform.password.data
            return redirect(
                url_for('users.register',
                        username=username,
                        email=email,
                        password=password))
        page = request.args.get('page', 1, type=int)
        user = User.query.filter_by(username=username).first_or_404()
        comments = Comment.query.filter_by(comment_author=user)\
            .order_by(Comment.date_posted.desc())\
            .paginate(page=page, per_page=5)
        return render_template('user_comments.html',
                               comments=comments,
                               user=user,
                               registerform=registerform,
                               modalshow=modalshow,
                               loginform=loginform,
                               loginmodalshow=loginmodalshow)
    except:
        flash(
            'Something went Wrong. Please check whether enterd details are correct',
            'warning')
        return redirect(url_for('main.home'))
Ejemplo n.º 11
0
def fbAdClicksPredict():
    #common ligin and signin routes
    loginmodalshow = 'close'
    loginform = LoginForm()
    if (loginform.validate_on_submit() == False and loginform.login.data):
        loginmodalshow = 'loginformmodal'
    if loginform.validate_on_submit() and loginform.login.data:
        remember = loginform.remember.data
        email = loginform.email.data
        password = loginform.password.data
        return redirect(
            url_for('users.login',
                    remember=remember,
                    email=email,
                    password=password))
    modalshow = 'close'
    registerform = RegistrationForm()
    if (registerform.validate_on_submit() == False
            and registerform.signup.data):
        modalshow = 'registerformmodal'
    if (registerform.validate_on_submit() and registerform.signup.data):
        username = registerform.username.data
        email = registerform.email.data
        password = registerform.password.data
        return redirect(
            url_for('users.register',
                    username=username,
                    email=email,
                    password=password))
    ################################

    prediction = AdPrediction()
    best_prediction = BestSolutions()

    day = request.args.get('weekday')
    gender = request.args.get('gender')
    txt = request.args.get('adText')
    startAge = int(request.args.get('minAge'))
    endAge = int(request.args.get('maxAge'))
    if (startAge >= endAge):
        flash('Age group is invalid!', 'warning')
        return redirect(url_for('main.facebook'))
    adSpends = float(request.args.get('adSpends'))  #usd
    ad_info = {
        'day': day,
        'gender': gender,
        'text': txt,
        'minAge': startAge,
        'maxAge': endAge,
        'spends': adSpends
    }
    all = 0
    male = 0
    female = 0
    if (gender == 'M'):
        male = 1
    if (gender == 'F'):
        female = 1
    if (gender == 'A'):
        all = 1
    mon = 0
    tue = 0
    wed = 0
    thu = 0
    fri = 0
    sat = 0
    sun = 0
    if (day == 'mon'):
        mon = 1
    elif (day == 'tue'):
        tue = 1
    elif (day == 'wed'):
        wed = 1
    elif (day == 'thu'):
        thu = 1
    elif (day == 'fri'):
        fri = 1
    elif (day == 'sat'):
        sat = 1
    elif (day == 'sun'):
        sun = 1

    impressions = prediction.impressions_from_money(adSpends)

    adSpends = prediction.usd_to_rub(adSpends)  #convert to rub
    final = {
        'mon': [mon],
        'tue': [tue],
        'wed': [wed],
        'thu': [thu],
        'fri': [fri],
        'sat': [sat],
        'sun': [sun],
        'male': [male],
        'female': [female],
        'all': [all],
        'AdTextRes': [prediction.get_ad_text_result(txt)],
        'startAge': [startAge],
        'endAge': [endAge],
        'AdImpressions': [impressions],
        'AdSpends': [adSpends]
    }
    final_features = pd.DataFrame.from_dict(final)
    outputt = prediction.predict(final_features)
    final_temp = dict(final)
    final_temp['AdSpends'] = adSpends

    # clicks=int((outputt[0]**2)**0.5)
    clicks = int(outputt[0])
    # clicks=adSpends

    bestSolutions = BestSolutions()

    # best_results=[bestSolutions.getBestGender(final,prediction),bestSolutions.getBestSpend(final,prediction),bestSolutions.getBestWeekDay(final_temp,prediction)]
    # best_results=[bestSolutions.getBestGender(final,prediction),bestSolutions.getBestSpend(final,prediction),{'sun':3,'mon':3,'tue':4,'wed':5,'thu':1,'fri':6,'sat':9}]
    # best_results=[[1,2,3],[[1,100],[2,200],[3,200],[4,200],[5,200]],{'sun':3,'mon':3,'tue':4,'wed':5,'thu':1,'fri':6,'sat':9}]

    #### ad form ###
    adform = AdForm()
    adpredict_model = 'close'
    if (adform.validate_on_submit() == False and adform.submit.data):
        adpredict_model = 'adpredictmodel'
    if adform.validate_on_submit() and adform.submit.data:
        gender = adform.gender.data
        adText = adform.adText.data
        weekday = adform.weekday.data
        minAge = adform.minAge.data
        maxAge = adform.maxAge.data
        adSpends = adform.adSpends.data
        return redirect(
            url_for('facebook.fbAdClicksPredict',
                    gender=gender,
                    adText=adText,
                    weekday=weekday,
                    minAge=minAge,
                    maxAge=maxAge,
                    adSpends=adSpends))

### handle bot detection
    botform = FbBotForm()
    botdetection_model = 'close'
    if (botform.validate_on_submit() == False and botform.submit.data):
        botdetection_model = 'botdetectionmodel'
    if botform.validate_on_submit() and botform.submit.data:
        link = botform.link.data
        return redirect(url_for('facebook.bot', link=link))

    return render_template('facebook_ad_display.html',
                           adform=adform,
                           ad_info=ad_info,
                           botform=botform,
                           registerform=registerform,
                           modalshow=modalshow,
                           loginform=loginform,
                           loginmodalshow=loginmodalshow,
                           results={'clicks': clicks})
Ejemplo n.º 12
0
def bot():
    #common ligin and signin routes
    loginmodalshow = 'close'
    loginform = LoginForm()
    if (loginform.validate_on_submit() == False and loginform.login.data):
        loginmodalshow = 'loginformmodal'
    if loginform.validate_on_submit() and loginform.login.data:
        remember = loginform.remember.data
        email = loginform.email.data
        password = loginform.password.data
        return redirect(
            url_for('users.login',
                    remember=remember,
                    email=email,
                    password=password))
    modalshow = 'close'
    registerform = RegistrationForm()
    if (registerform.validate_on_submit() == False
            and registerform.signup.data):
        modalshow = 'registerformmodal'
    if registerform.validate_on_submit() and registerform.signup.data:
        username = registerform.username.data
        email = registerform.email.data
        password = registerform.password.data
        return redirect(
            url_for('users.register',
                    username=username,
                    email=email,
                    password=password))
    ################################
    profile_link = request.args["link"]
    detection = BotAccountDetection()
    # try:
    info = detection.get_info(profile_link)
    # except:
    #     flash('Link you entered is not valid or some issue with your connection  ', 'warning')
    #     return redirect(url_for('main.facebook'))
    values = detection.calculate(info)
    if (values['neg'] == 100):
        flash('The profile link you entered is not valid!', 'warning')
        return redirect(url_for('main.facebook'))

    #### ad form ###
    adform = AdForm()
    adpredict_model = 'close'
    if (adform.validate_on_submit() == False and adform.submit.data):
        adpredict_model = 'adpredictmodel'
    if adform.validate_on_submit() and adform.submit.data:
        gender = adform.gender.data
        adText = adform.adText.data
        weekday = adform.weekday.data
        minAge = adform.minAge.data
        maxAge = adform.maxAge.data
        adSpends = adform.adSpends.data
        return redirect(
            url_for('facebook.fbAdClicksPredict',
                    gender=gender,
                    adText=adText,
                    weekday=weekday,
                    minAge=minAge,
                    maxAge=maxAge,
                    adSpends=adSpends))

    ### handle bot detection
    botform = FbBotForm()
    botdetection_model = 'close'
    if (botform.validate_on_submit() == False and botform.submit.data):
        botdetection_model = 'botdetectionmodel'
    if botform.validate_on_submit() and botform.submit.data:
        link = botform.link.data
        return redirect(url_for('facebook.bot', link=link))

    ### get display info ###
    display_info = {}
    fields = []
    list_fields = []
    for field in info:
        if (field == "tagged_photo_count"):
            if (info[field] > 0):
                display_info["Tagged Photos"] = "Yes"
                fields.append("Tagged Photos")
        elif (field == "Family Members"):
            if (len(info[field][1]) > 0):
                display_info["Family Member"] = info[field][1]
                list_fields.append("Family Member")
        elif (type(info[field]) == list):
            if (info[field][0] != None and info[field][0] != ""):
                display_info[field] = info[field]
                list_fields.append(field)
        else:
            if (info[field] != None and info[field] != ""):
                display_info[field] = info[field]
                fields.append(field)

    return render_template('facebook_bot_detection.html',
                           adform=adform,
                           botform=botform,
                           list_fields=list_fields,
                           fields=fields,
                           bot_info=info,
                           display_info=display_info,
                           cal_values=values,
                           registerform=registerform,
                           modalshow=modalshow,
                           loginform=loginform,
                           loginmodalshow=loginmodalshow)
Ejemplo n.º 13
0
def bot_account_detection(name):
    try:
        loginmodalshow = 'close'
        loginform = LoginForm()
        if (loginform.validate_on_submit() == False and loginform.login.data):
            loginmodalshow = 'loginformmodal'
        if loginform.validate_on_submit() and loginform.login.data:
            remember = loginform.remember.data
            email = loginform.email.data
            password = loginform.password.data
            return redirect(
                url_for('users.login',
                        remember=remember,
                        email=email,
                        password=password))
        modalshow = 'close'
        registerform = RegistrationForm()
        if (registerform.validate_on_submit() == False
                and registerform.signup.data):
            modalshow = 'registerformmodal'
        if registerform.validate_on_submit() and registerform.signup.data:
            username = registerform.username.data
            email = registerform.email.data
            password = registerform.password.data
            return redirect(
                url_for('users.register',
                        username=username,
                        email=email,
                        password=password))
        twitter_client = TwitterClient()
        user = twitter_client.get_user(name)
        prediction = Prediction()
        created_at = user.created_at
        year = created_at.year
        month = created_at.month
        day = created_at.day
        duration = prediction.get_time_period(year, month, day)
        id = user.id
        description = prediction.sentiment_description(user.description)
        followers_count = user.followers_count
        friends_count = user.friends_count
        listed_count = user.listed_count
        favourites_count = user.favourites_count
        verified = prediction.encode_verified(user.verified)
        statuses_count = user.statuses_count
        default_profile = prediction.encode_default_profile(
            user.default_profile)
        default_profile_image = prediction.encode_default_profile_image(
            user.default_profile_image)
        has_extended_profile = prediction.encode_has_extended_profile(
            user.has_extended_profile)
        pred_list = [
            description, followers_count, friends_count, listed_count,
            favourites_count, verified, statuses_count, default_profile,
            default_profile_image, has_extended_profile, year, month, day,
            duration
        ]
        pred_list = np.array(pred_list)
        #import model and predict
        pred_result = prediction.predict([pred_list])
        verified = 'NOTVERIFIED'
        badge = 'badge-danger'
        if (user.verified):
            verified = 'VERIFIED'
            badge = 'badge-success'

        return render_template('bot_detection.html',
                               user=user,
                               pred_result=pred_result,
                               registerform=registerform,
                               modalshow=modalshow,
                               loginform=loginform,
                               verified=verified,
                               badge=badge,
                               loginmodalshow=loginmodalshow)
    except:
        flash(
            'Something went Wrong. Please check whether enterd details are correct',
            'warning')
        return redirect(url_for('main.twitter'))
Ejemplo n.º 14
0
def user_tweets(name):
    try:
        pred_text = request.args.get('tweet')
        #time = request.args.get('time')
        #hour = int(time[0:2])
        #minute = int(time[3:5])
        if (pred_text == None):
            flash('prdiction tweet text cannot be null', 'warning')
            return redirect(url_for('main.twitter'))
        loginmodalshow = 'close'
        loginform = LoginForm()
        if (loginform.validate_on_submit() == False and loginform.login.data):
            loginmodalshow = 'loginformmodal'
        if loginform.validate_on_submit() and loginform.login.data:
            remember = loginform.remember.data
            email = loginform.email.data
            password = loginform.password.data
            return redirect(
                url_for('users.login',
                        remember=remember,
                        email=email,
                        password=password))
        modalshow = 'close'
        registerform = RegistrationForm()
        if (registerform.validate_on_submit() == False
                and registerform.signup.data):
            modalshow = 'registerformmodal'
        if registerform.validate_on_submit() and registerform.signup.data:
            username = registerform.username.data
            email = registerform.email.data
            password = registerform.password.data
            return redirect(
                url_for('users.register',
                        username=username,
                        email=email,
                        password=password))
        twitter_client = TwitterClient()
        user = twitter_client.get_user(name)
        tweet_analyzer = TweetAnalyzer()
        tweets = twitter_client.get_tweets_of_a_user(name, 1000)
        tweets_likes_prediction = TweetLikesPrediction()
        texts = []
        likes = []
        retweetscount = []
        hours = []
        minutes = []
        for tweet in tweets:
            minutes.append(tweet.created_at.minute)
            hours.append(tweet.created_at.hour)
            #print(minutes)
            if (hasattr(tweet, 'retweeted_status')):
                texts.append(tweet.retweeted_status.full_text)
            else:
                texts.append(tweet.full_text)
            likes.append(tweet.favorite_count)
            retweetscount.append(tweet.retweet_count)
        #texts = np.array(texts)
        tokenizer = tweets_likes_prediction.set_tokenizer(texts)
        sequences = tweets_likes_prediction.texts_to_sequences(
            texts, tokenizer)
        padded_sequences = tweets_likes_prediction.get_padded_sequeces(
            sequences)
        # features=[]
        # for i in range(0,len(likes)):
        #     feature = np.append(padded_sequences[i],likes[i])
        #     features.append(feature)
        # features = np.array(features)
        nplikes = np.array(likes)
        #nphours = np.array(hours)
        #npminutes = np.array(minutes)
        npretweetscount = np.array(retweetscount)
        # features =[]
        # for i in range(0, len(hours)):
        #     l = np.append(padded_sequences[i], hours[i])
        #     l2 = np.append(l, minutes[i])
        #     features.append(l2)
        # npfeatures = np.array(features)
        #print(npfeatures[0])
        #print(padded_sequences[0])
        retweetmodel = tweets_likes_prediction.train_model(
            padded_sequences, npretweetscount)
        model = tweets_likes_prediction.train_model(padded_sequences, nplikes)
        tweetcount = []
        for i in range(0, len(likes)):
            tweetcount.append(i)
        pred_text = [pred_text]
        pred_sequence = tweets_likes_prediction.texts_to_sequences(
            pred_text, tokenizer)
        maxlength = padded_sequences[0].size
        pred_padded_sequence = tweets_likes_prediction.get_padded_sequeces_with_maxlength(
            pred_sequence, maxlength)
        #result = pred_padded_sequence
        #pred_padded_sequence_with_hour = np.append(pred_padded_sequence[0],hour)
        #pred_padded_sequence_with_minute = np.append(pred_padded_sequence_with_hour,minute)
        #pred_padded_sequence_with_time = np.array([pred_padded_sequence_with_minute])
        result = model.predict(pred_padded_sequence)
        retweet_result = retweetmodel.predict(pred_padded_sequence)
        intResult = abs(int(result))
        intRetweetResult = abs(int(retweet_result))
        return render_template('user_tweets.html',
                               result=intResult,
                               retweet_result=intRetweetResult,
                               retweetscount=retweetscount,
                               likes=likes,
                               tweetcount=tweetcount,
                               registerform=registerform,
                               modalshow=modalshow,
                               loginform=loginform,
                               loginmodalshow=loginmodalshow,
                               user=user,
                               pred_text=pred_text)
    except:
        flash(
            'Something went Wrong. Please check whether enterd details are correct',
            'warning')
        return redirect(url_for('main.twitter'))
Ejemplo n.º 15
0
def twitter():
    try:
        loginmodalshow = 'close'
        loginform = LoginForm()
        if (loginform.validate_on_submit() == False and loginform.login.data):
            loginmodalshow = 'loginformmodal'
        if loginform.validate_on_submit() and loginform.login.data:
            remember = loginform.remember.data
            email = loginform.email.data
            password = loginform.password.data
            return redirect(
                url_for('users.login',
                        remember=remember,
                        email=email,
                        password=password))
        modalshow = 'close'
        registerform = RegistrationForm()
        if (registerform.validate_on_submit() == False
                and registerform.signup.data):
            modalshow = 'registerformmodal'
        if registerform.validate_on_submit() and registerform.signup.data:
            username = registerform.username.data
            email = registerform.email.data
            password = registerform.password.data
            return redirect(
                url_for('users.register',
                        username=username,
                        email=email,
                        password=password))

        botform = BotForm()
        botmodal = 'close'
        if (botform.validate_on_submit() == False and botform.submit.data):
            botmodal = 'botdetectionmodel'
        if botform.validate_on_submit() and botform.submit.data:
            bot_account_name = botform.name.data
            return redirect(
                url_for('twitter.bot_account_detection',
                        name=bot_account_name))

        hashtagform = HashtagForm()
        hashtagmodal = 'close'
        if (hashtagform.validate_on_submit() == False
                and hashtagform.hashtagsubmit.data):
            hashtagmodal = 'hashtagmodel'
        if hashtagform.validate_on_submit() and hashtagform.hashtagsubmit.data:
            hashtag = hashtagform.hashtag.data
            return redirect(url_for('twitter.hashtag_tweets', hashtag=hashtag))

        screennamemodal = 'close'
        screennameform = NameForm()
        if (screennameform.validate_on_submit() == False
                and screennameform.search.data):
            screennamemodal = 'searchforaccount'
        if screennameform.validate_on_submit() and screennameform.search.data:
            screen_name = screennameform.name.data
            return redirect(url_for('twitter.user_details', name=screen_name))

        predtweetmodal = 'close'
        tweetform = TweetForm()
        if (tweetform.validate_on_submit() == False
                and tweetform.likespredict.data):
            predtweetmodal = 'likespredmodal'
        if tweetform.validate_on_submit() and tweetform.likespredict.data:
            screen_name = tweetform.name.data
            tweet = tweetform.tweet.data
            #time = tweetform.time.data
            return redirect(
                url_for('twitter.user_tweets', name=screen_name, tweet=tweet))

        return render_template('twitter.html',
                               title='Twitter',
                               tweetform=tweetform,
                               screennameform=screennameform,
                               botform=botform,
                               hashtagform=hashtagform,
                               registerform=registerform,
                               modalshow=modalshow,
                               loginform=loginform,
                               loginmodalshow=loginmodalshow,
                               predtweetmodal=predtweetmodal,
                               screennamemodal=screennamemodal,
                               botmodal=botmodal,
                               hashtagmodal=hashtagmodal)
    except:
        flash(
            'Something went Wrong. Please check weather enterd details are correct',
            'warning')
        return redirect(url_for('main.home'))
Ejemplo n.º 16
0
def youtube():
    try:
        loginmodalshow = 'close'
        loginform = LoginForm()
        if (loginform.validate_on_submit() == False and loginform.login.data):
            loginmodalshow = 'loginformmodal'
        if loginform.validate_on_submit() and loginform.login.data:
            remember = loginform.remember.data
            email = loginform.email.data
            password = loginform.password.data
            return redirect(
                url_for('users.login',
                        remember=remember,
                        email=email,
                        password=password))

        modalshow = 'close'
        registerform = RegistrationForm()
        if (registerform.validate_on_submit() == False
                and registerform.signup.data):
            modalshow = 'registerformmodal'
        if registerform.validate_on_submit() and registerform.signup.data:
            username = registerform.username.data
            email = registerform.email.data
            password = registerform.password.data
            return redirect(
                url_for('users.register',
                        username=username,
                        email=email,
                        password=password))

        channeldetailmodal = 'close'
        channeldetailform = ChannelDetailForm()
        if (channeldetailform.validate_on_submit() == False
                and channeldetailform.search.data):
            channeldetailmodal = 'channeldetails'
        if channeldetailform.validate_on_submit(
        ) and channeldetailform.search.data:
            channel_id = channeldetailform.name.data
            return redirect(
                url_for('youtube.viewChannelDetails', name=channel_id))

        sentimentanalysismodal = 'close'
        sentimentanalysisform = SentimentAnalysisForm()
        if (sentimentanalysisform.validate_on_submit() == False
                and sentimentanalysisform.searchSent.data):
            sentimentanalysismodal = 'analysecomments'
        if sentimentanalysisform.validate_on_submit(
        ) and sentimentanalysisform.searchSent.data:
            video_id = sentimentanalysisform.name.data
            return redirect(url_for('youtube.analyseComments', name=video_id))

        viewpredictionmodal = 'close'
        viewpredictionform = ViewPredictionForm()
        if (viewpredictionform.validate_on_submit() == False
                and viewpredictionform.viewspredict.data):
            viewpredictionmodal = 'predictviews'
        if viewpredictionform.validate_on_submit(
        ) and viewpredictionform.viewspredict.data:
            channel_id = viewpredictionform.channel.data
            category_id = viewpredictionform.category.data
            dur = viewpredictionform.length.data
            return redirect(
                url_for('youtube.predictViews',
                        name=channel_id,
                        dur=dur,
                        category_id=category_id))

        viralvideomodal = 'close'
        viralvideofrom = ViralVideoForm()
        if (viralvideofrom.validate_on_submit() == False):
            viralvideomodal = 'viralvideos'
        if viralvideofrom.validate_on_submit():
            return redirect(url_for('youtube.viralVideos'))

        return render_template('youtube.html',
                               title='Youtube',
                               viewpredictionform=viewpredictionform,
                               viewpredictionmodal=viewpredictionmodal,
                               sentimentanalysisform=sentimentanalysisform,
                               registerform=registerform,
                               channeldetailform=channeldetailform,
                               sentimentanalysismodal=sentimentanalysismodal,
                               channeldetailmodal=channeldetailmodal,
                               modalshow=modalshow,
                               loginform=loginform,
                               loginmodalshow=loginmodalshow,
                               viralvideomodal=viralvideomodal,
                               viralvideofrom=viralvideofrom)
    except:
        flash(
            'Something went Wrong. Please check weather enterd details are correct',
            'warning')
        return redirect(url_for('main.home'))
Ejemplo n.º 17
0
def sentiment():
    #common ligin and signin routes
    loginmodalshow = 'close'
    loginform = LoginForm()
    if (loginform.validate_on_submit() == False and loginform.login.data):
        loginmodalshow = 'loginformmodal'
    if loginform.validate_on_submit() and loginform.login.data:
        remember = loginform.remember.data
        email = loginform.email.data
        password = loginform.password.data
        return redirect(
            url_for('users.login',
                    remember=remember,
                    email=email,
                    password=password))
    modalshow = 'close'
    registerform = RegistrationForm()
    if (registerform.validate_on_submit() == False
            and registerform.signup.data):
        modalshow = 'registerformmodal'
    if registerform.validate_on_submit() and registerform.signup.data:
        username = registerform.username.data
        email = registerform.email.data
        password = registerform.password.data
        return redirect(
            url_for('users.register',
                    username=username,
                    email=email,
                    password=password))
    ################################
    pos_imojies = {
        '1f600': 0.2,
        '1f603': 0.2,
        '1f604': 0.2,
        '1f601': 0.2,
        '1f606': 0.2,
        '1f605': 0.2,
        '1f602': 0.2,
        '1f923': 0.2,
        '263a': 0.1,
        '1f60a': 0.1,
        '1f607': 0.1,
        '1f642': 0.2,
        '1f643': 0.1,
        '1f609': 0.1,
        '1f60d': 0.3,
        '1f970': 0.3,
        '1f618': 0.3,
        '1f617': 0.3,
        '1f619': 0.3,
        '1f61a': 0.3,
        '1f60b': 0.3,
        '1f61b': 0.3,
        '1f61d': 0.3,
        '1f61c': 0.3,
        '1f92a': 0.3,
        '1f60e': 0.1,
        '1f929': 0.3,
        '1f973': 0.3,
        '1f917': 0.2,
        '1f92d': 0.1,
        '1f636': 0.3,
        '1f62c': 0.3,
        '1f912': 0.2,
        '1f911': 0.2,
        '1f921': 0.1,
        '1f4a9': 0.3,
        '1f47b': 0.3,
        '1f480': 0.3,
        '2620': 0.3,
        '1f47e': 0.3,
        '1f639': 0.2,
        '1f63b': 0.2,
        '1f63c': 0.2,
        '1f63d': 0.2,
        '1f640': 0.2,
        '1f63f': 0.2,
        '1f63e': 0.2,
        '1f932': 0.2,
        '1f450': 0.2,
        '1f64c': 0.2,
        '1f44f': 0.2,
        '1f91d': 0.2,
        '1f44d': 0.2,
        '1f44e': 0.2,
        '1f44a': 0.2,
        '270a': 0.2,
        '1f91b': 0.2,
        '1f91c': 0.2,
        '1f91e': 0.2,
        '270c': 0.2,
        '1f91f': 0.2,
        '1f918': 0.2,
        '1f44c': 0.2,
        '1f448': 0.2,
        '1f449': 0.2,
        '1f446': 0.2,
        '1f447': 0.2,
        '261d': 0.2,
        '270b': 0.2,
        '1f91a': 0.2,
        '1f590': 0.2,
        '1f596': 0.2,
        '2764': 0.3,
        '1f9e1': 0.3,
        '1f49b': 0.3,
        '1f49a': 0.3,
        '1f499': 0.3,
        '1f49c': 0.3,
        '1f5a4': 0.3,
        '2763': 0.3,
        '1f495': 0.3,
        '1f49e': 0.3,
        '1f493': 0.3,
        '1f497': 0.3,
        '1f496': 0.3,
        '1f498': 0.3,
        '1f49d': 0.3,
        '1f49f': 0.3,
        '262e': 0.3,
        '271d': 0.3,
        '262a': 0.3,
        '1f549': 0.3,
        '2638': 0.3,
        '2721': 0.3,
        '1f52f': 0.3
    }

    neu_imojies = {
        '1f60c': 0.3,
        '1f9d0': 0.2,
        '1f913': 0.2,
        '1f914': 0.2,
        '1f92b': 0.2,
        '1f925': 0.2,
        '1f610': 0.2,
        '1f611': 0.2,
        '1f626': 0.2,
        '1f479': 0.1,
        '1f47a': 0.1,
        '1f47d': 0.3,
        '1f916': 0.3,
        '1f638': 0.3
    }

    neg_imojies = {
        '1f928': 0.3,
        '1f60f': 0.3,
        '1f612': 0.3,
        '1f61e': 0.3,
        '1f614': 0.3,
        '1f61f': 0.3,
        '1f615': 0.3,
        '1f641': 0.3,
        '2639': 0.3,
        '1f623': 0.3,
        '1f616': 0.3,
        '1f62b': 0.3,
        '1f629': 0.3,
        '1f97a': 0.3,
        '1f622': 0.3,
        '1f62d': 0.3,
        '1f624': 0.3,
        '1f620': 0.3,
        '1f621': 0.3,
        '1f92c': 0.3,
        '1f92f': 0.3,
        '1f633': 0.3,
        '1f975': 0.3,
        '1f976': 0.3,
        '1f631': 0.3,
        '1f628': 0.3,
        '1f630': 0.3,
        '1f625': 0.3,
        '1f613': 0.2,
        '1f644': 0.3,
        '1f62f': 0.3,
        '1f627': 0.3,
        '1f62e': 0.3,
        '1f632': 0.3,
        '1f634': 0.3,
        '1f924': 0.3,
        '1f62a': 0.3,
        '1f635': 0.3,
        '1f910': 0.3,
        '1f974': 0.3,
        '1f922': 0.3,
        '1f92e': 0.3,
        '1f927': 0.3,
        '1f637': 0.3,
        '1f915': 0.3,
        '1f920': 0.3,
        '1f608': 0.3,
        '1f47f': 0.3,
        '1f383': 0.1,
        '1f63a': 0.3,
        '1f494': 0.3
    }

    # if(request.files['upload']):
    f = request.files['upload']
    try:
        data = f.read()
        soup = BeautifulSoup(data, 'html.parser')
    except:
        flash("Please upload the File!", 'warning')
        return redirect(url_for("main.facebook"))
    comments = []
    try:
        # if(True):
        main_content = soup.findAll('div', {'class': 'cwj9ozl2 tvmbv18p'})
        post = main_content[0]
        comments_section = post.findAll('ul')[1]
        commentss = comments_section.findAll('li')
        commentss = commentss[:]
        for comment in commentss:
            # if(True):
            try:
                try:
                    name = comment.find(
                        'span', {
                            'class':
                            'oi732d6d ik7dh3pa d2edcug0 qv66sw1b c1et5uql a8c37x1j hop8lmos enqfppq2 e9vueds3 j5wam9gi lrazzd5p oo9gr5id'
                        }).text
                except:
                    name = comment.find(
                        'span', {
                            'class':
                            'oi732d6d ik7dh3pa d2edcug0 hpfvmrgz qv66sw1b c1et5uql a8c37x1j hop8lmos enqfppq2 e9vueds3 j5wam9gi lrazzd5p oo9gr5id'
                        }).text

                link = comment.find(
                    'a', {
                        'class':
                        'oajrlxb2 g5ia77u1 qu0x051f esr5mh6w e9989ue4 r7d6kgcz rq0escxv nhd2j8a9 nc684nl6 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys rz4wbd8a qt6c0cv9 a8nywdso i1ao9s8h esuyzwwr f1sip0of lzcic4wl gmql0nx0 gpro0wi8'
                    }).get('href')

                try:
                    comment_text = comment.find(
                        'span', {
                            'class':
                            'oi732d6d ik7dh3pa d2edcug0 qv66sw1b c1et5uql a8c37x1j muag1w35 enqfppq2 jq4qci2q a3bd9o3v knj5qynh oo9gr5id'
                        }).text
                except:
                    comment_text = comment.find(
                        'span', {
                            'class':
                            'oi732d6d ik7dh3pa d2edcug0 hpfvmrgz qv66sw1b c1et5uql a8c37x1j muag1w35 enqfppq2 jq4qci2q a3bd9o3v knj5qynh oo9gr5id'
                        }).text

                imoji_spans = comment.findAll(
                    'span', {
                        'class':
                        'q9uorilb tbxw36s4 knj5qynh kvgmc6g5 ditlmg2l oygrvhab nvdbi5me fgm26odu gl3lb2sf hhz5lgdu'
                    })

                imojies = []
                for imoji_span in imoji_spans:
                    imoji_src = imoji_span.find('img')['src']
                    image = imoji_span.find('img')['alt']
                    comment_text = comment_text + image
                    imojies.append((imoji_src.split('/'))[-1].split('.')[0])
                comments.append([comment_text, name, link, 0, imojies])
            except:
                # else:
                x = 'nothing'
    except:
        # else:
        flash('Invalid File! Try again', 'warning')
        return redirect(url_for("main.facebook"))
    check = []
    pos = 0
    neu = 0
    neg = 0
    pos_list = []
    neu_list = []
    neg_list = []

    if (len(comments) == 0):
        flash("Your file doesn't contain any comments", 'warning')
        return redirect(url_for("main.facebook"))
    maxx = 20
    got = 0
    for i in range(len(comments)):
        if (len(comments[i][0]) > 0):
            if (got >= maxx):
                break
            got += 1
            comment = comments[i]
            text = comment[0]
            word = text
            sent_tokenizer = PunktSentenceTokenizer(text)
            sents = sent_tokenizer.tokenize(text)
            porter_stemmer = PorterStemmer()

            nltk_tokens = nltk.word_tokenize(text)
            wordnet_lemmatizer = WordNetLemmatizer()
            nltk_tokens = nltk.word_tokenize(text)

            text = nltk.word_tokenize(text)
            sid = SentimentIntensityAnalyzer()
            tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')

            scores = sid.polarity_scores(word)
            c = scores['compound']
            del scores['compound']

            # add imoji values
            imojies = comments[i][4]

            neg_temp = scores['neg']
            pos_temp = scores['pos']
            neu_temp = scores['neu']
            scores['neg'] = 0
            scores['pos'] = 0
            scores['neu'] = 0
            found = False
            for imoji in imojies:
                if (imoji in pos_imojies):
                    scores['pos'] += pos_imojies[imoji]
                    found = True
                elif (imoji in neu_imojies):
                    found = True
                    scores['neu'] += neu_imojies[imoji]
                elif (imoji in neg_imojies):
                    found = True
                    scores['neg'] += neg_imojies[imoji]
            if (found == False):
                scores['neg'] = neg_temp
                scores['pos'] = pos_temp
                scores['neu'] = neu_temp
            res = max(scores.items(), key=operator.itemgetter(1))[0]
            # comments[i].append(c)
            # comments[i].append(scores)
            if (res == 'neu'):
                neu_list.append(comments[i])
            elif (res == 'pos'):
                pos_list.append(comments[i])
            elif (res == 'neg'):
                neg_list.append(comments[i])
            neu += scores['neu']
            pos += scores['pos']
            neg += scores['neg']

        # except:
        else:
            print()
            #doing nothing
    pos_p = pos * 100 / (neg + pos + neu)
    neu_p = neu * 100 / (neg + pos + neu)
    neg_p = neg * 100 / (neg + pos + neu)
    post_result = {"Negative": neg_p, "Positive": pos_p, "Neutral": neu_p}
    post_result["final"] = max(post_result.items(),
                               key=operator.itemgetter(1))[0]
    all_comments = [pos_list, neu_list, neg_list]

    #### ad form ###
    adform = AdForm()
    adpredict_model = 'close'
    if (adform.validate_on_submit() == False and adform.submit.data):
        adpredict_model = 'adpredictmodel'
    if adform.validate_on_submit() and adform.submit.data:
        gender = adform.gender.data
        adText = adform.adText.data
        weekday = adform.weekday.data
        minAge = adform.minAge.data
        maxAge = adform.maxAge.data
        adSpends = adform.adSpends.data
        return redirect(
            url_for('facebook.fbAdClicksPredict',
                    gender=gender,
                    adText=adText,
                    weekday=weekday,
                    minAge=minAge,
                    maxAge=maxAge,
                    adSpends=adSpends))

### handle bot detection
    botform = FbBotForm()
    botdetection_model = 'close'
    if (botform.validate_on_submit() == False and botform.submit.data):
        botdetection_model = 'botdetectionmodel'
        # return redirect(url_for('main.facebook'))
    if botform.validate_on_submit() and botform.submit.data:
        link = botform.link.data
        return redirect(url_for('facebook.bot', link=link))

    return render_template('facebook_sentiment.html',
                           comments=comments,
                           adform=adform,
                           botform=botform,
                           all_comments=all_comments,
                           post_result=post_result,
                           registerform=registerform,
                           modalshow=modalshow,
                           loginform=loginform,
                           loginmodalshow=loginmodalshow)
Ejemplo n.º 18
0
def viewChannelDetails(name):
    loginmodalshow = 'close'
    loginform = LoginForm()
    if (loginform.validate_on_submit() == False and loginform.login.data):
        loginmodalshow = 'loginformmodal'
    if loginform.validate_on_submit() and loginform.login.data:
        remember = loginform.remember.data
        email = loginform.email.data
        password = loginform.password.data
        return redirect(
            url_for('users.login',
                    remember=remember,
                    email=email,
                    password=password))
    modalshow = 'close'
    registerform = RegistrationForm()
    if (registerform.validate_on_submit() == False
            and registerform.signup.data):
        modalshow = 'registerformmodal'
    if registerform.validate_on_submit() and registerform.signup.data:
        username = registerform.username.data
        email = registerform.email.data
        password = registerform.password.data
        return redirect(
            url_for('users.register',
                    username=username,
                    email=email,
                    password=password))

    try:
        Cid, vid, view, sub, name, description, Date, privacy, featured, colour, bannerurl, location, customurl, language = getChannelData(
            name)
    #colour = "#ffffff"
    except:
        flash(
            "Couldn't get data. Please check whether entered details are correct",
            "warning")
        return redirect(url_for('main.youtube'))

    viewratio = (round(view / vid))
    url = "https://www.youtube.com/channel/" + Cid

    return render_template('viewchannel.html',
                           customurl=customurl,
                           location=location,
                           viewratio=viewratio,
                           Cid=Cid,
                           featured=featured,
                           colour=colour,
                           bannerurl=bannerurl,
                           privacy=privacy,
                           description=description,
                           Date=Date,
                           name=name,
                           vid=vid,
                           view=view,
                           sub=sub,
                           loginmodalshow=loginmodalshow,
                           loginform=loginform,
                           modalshow=modalshow,
                           registerform=registerform,
                           url=url,
                           language=language)
Ejemplo n.º 19
0
def analyseComments(name):
    loginmodalshow = 'close'
    loginform = LoginForm()
    if (loginform.validate_on_submit() == False and loginform.login.data):
        loginmodalshow = 'loginformmodal'
    if loginform.validate_on_submit() and loginform.login.data:
        remember = loginform.remember.data
        email = loginform.email.data
        password = loginform.password.data
        return redirect(
            url_for('users.login',
                    remember=remember,
                    email=email,
                    password=password))
    modalshow = 'close'
    registerform = RegistrationForm()
    if (registerform.validate_on_submit() == False
            and registerform.signup.data):
        modalshow = 'registerformmodal'
    if registerform.validate_on_submit() and registerform.signup.data:
        username = registerform.username.data
        email = registerform.email.data
        password = registerform.password.data
        return redirect(
            url_for('users.register',
                    username=username,
                    email=email,
                    password=password))

    negcom = 0
    poscom = 0
    neucom = 0
    exPosCom = []
    exNegCom = []
    exNeuCom = []
    analysedCom = 0

    char = [
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
        'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', "👏🏽", "👌", "♥️", "👍",
        "😍", "😀", "🔥", "💪", "✌️", "😘", "❤", "😊"
    ]

    comments, replyCount = getComments(name)
    topcom = len(comments)

    for comment in comments:
        for c in char:
            if c in comment:
                break
        else:
            print(comment)
            continue
        val = sentimentAnalysis(comment)
        analysedCom += 1
        if val == 1:
            poscom += 1
            exPosCom.append(comment)
        elif val == -1:
            negcom += 1
            exNegCom.append(comment)
        else:
            neucom += 1
            exNeuCom.append(comment)
        #print(comment,val)
    title, des, Date, channel, categoryID, language, duration, privacy, status, views, likes, dislikes = getVideoDetails(
        name)
    #des = des.replace("\n","<br/>")
    category = getVideoCategory(categoryID)
    url = "https://www.youtube.com/watch?v=" + name
    exPosCom = exPosCom[:4]
    exNegCom = exNegCom[:4]
    exNeuCom = exNeuCom[:4]

    return render_template('commentanalysis.html',
                           analysedCom=analysedCom,
                           exPosCom=exPosCom,
                           exNegCom=exNegCom,
                           exNeuCom=exNeuCom,
                           name=name,
                           topcom=topcom,
                           neucom=neucom,
                           negcom=negcom,
                           poscom=poscom,
                           replyCount=replyCount,
                           likes=likes,
                           loginmodalshow=loginmodalshow,
                           loginform=loginform,
                           categoryID=categoryID,
                           language=language,
                           duration=duration,
                           privacy=privacy,
                           status=status,
                           category=category,
                           title=title,
                           des=des,
                           Date=Date,
                           channel=channel,
                           modalshow=modalshow,
                           registerform=registerform,
                           views=views,
                           dislikes=dislikes,
                           url=url)
Ejemplo n.º 20
0
def viralVideos():

    try:
        loginmodalshow = 'close'
        loginform = LoginForm()
        if (loginform.validate_on_submit() == False and loginform.login.data):
            loginmodalshow = 'loginformmodal'
        if loginform.validate_on_submit() and loginform.login.data:
            remember = loginform.remember.data
            email = loginform.email.data
            password = loginform.password.data
            return redirect(
                url_for('users.login',
                        remember=remember,
                        email=email,
                        password=password))
        modalshow = 'close'
        registerform = RegistrationForm()
        if (registerform.validate_on_submit() == False
                and registerform.signup.data):
            modalshow = 'registerformmodal'
        if registerform.validate_on_submit() and registerform.signup.data:
            username = registerform.username.data
            email = registerform.email.data
            password = registerform.password.data
            return redirect(
                url_for('users.register',
                        username=username,
                        email=email,
                        password=password))

        data = (pd.read_csv(
            'social_media_analysis/youtube/codes/ViralVideoAnalysis/data.csv'))
        analyzedData = (pd.read_csv(
            'social_media_analysis/youtube/codes/ViralVideoAnalysis/analysedData.csv'
        ))

        language = data.iloc[:, 7].values
        location = data.iloc[:, 14].values
        category = data.iloc[:, 6].values
        likePerc = data.iloc[:, 15].values[:15]
        dislikePerc = data.iloc[:, 16].values[:15]
        likeDisRatio = data.iloc[:, 17].values[:15]

        languagePair = []
        locationPair = []
        categoryPair = []

        dur = analyzedData.iloc[:, 1].values
        sub = (analyzedData.iloc[:, 4].values)[:6]
        vid = (analyzedData.iloc[:, 3].values)[:6]
        days = (analyzedData.iloc[:, 2].values)[:7]
        views = (analyzedData.iloc[:, 5].values)[:7]

        for lan in sorted(set(language)):
            count = list(language).count(lan)
            #print(lan,count)
            languagePair.append([lan, count])

        for loc in sorted(set(location)):
            count = list(location).count(loc)
            #print(loc,count)
            locationPair.append([loc, count])

        for cat in sorted(set(category)):
            count = list(category).count(cat)
            #print(cat,count)
            categoryPair.append([cat, count])

        return render_template('viralVideo.html',
                               loginmodalshow=loginmodalshow,
                               loginform=loginform,
                               modalshow=modalshow,
                               registerform=registerform,
                               languagePair=languagePair,
                               locationPair=locationPair,
                               categoryPair=categoryPair,
                               likePerc=likePerc,
                               dislikePerc=dislikePerc,
                               likeDisRatio=likeDisRatio,
                               dur=dur,
                               sub=sub,
                               vid=vid,
                               days=days,
                               views=views)

    except:
        flash('Something went wrong. Please try again.', 'warning')
        return redirect(url_for('main.youtube'))
Ejemplo n.º 21
0
def predictViews(name):

    length = request.args.get('dur')
    cat = request.args.get('category_id')

    loginmodalshow = 'close'
    loginform = LoginForm()
    if (loginform.validate_on_submit() == False and loginform.login.data):
        loginmodalshow = 'loginformmodal'
    if loginform.validate_on_submit() and loginform.login.data:
        remember = loginform.remember.data
        email = loginform.email.data
        password = loginform.password.data
        return redirect(
            url_for('users.login',
                    remember=remember,
                    email=email,
                    password=password))
    modalshow = 'close'
    registerform = RegistrationForm()
    if (registerform.validate_on_submit() == False
            and registerform.signup.data):
        modalshow = 'registerformmodal'
    if registerform.validate_on_submit() and registerform.signup.data:
        username = registerform.username.data
        email = registerform.email.data
        password = registerform.password.data
        return redirect(
            url_for('users.register',
                    username=username,
                    email=email,
                    password=password))

    varV1 = 0.00156376762
    varV2 = 2.08209400
    varV3 = 0.0134076844
    varV4 = 0.0000533043632
    varV5 = -0.0107301493
    varV6 = -0.00151770880

    varL1 = 0.000491893046
    varL2 = 0.082029009
    varL3 = 0.00648799428
    varL4 = 0.0000146301918
    varL5 = -0.00216844026
    varL6 = -0.00053356926

    try:
        Cid, vid, view, sub, name, description, Date, privacy, featured, colour, bannerurl, location, customurl, language = getChannelData(
            name)

    except:
        flash(
            "Couldn't get data. Please check whether entered details are correct",
            "warning")
        return redirect(url_for('main.youtube'))

    Date = datetime.strptime(Date, '%Y-%m-%d').date()
    today = date.today()
    days = abs(Date - today).days

    viewPred = int(varV1 * int(vid) + varV2 * int(sub) + varV3 * int(days) +
                   varV4 * int(view) + varV5 * int(cat) + varV6 * int(length))
    likePred = int(varL1 * int(vid) + varL2 * int(sub) + varL3 * int(days) +
                   varL4 * int(view) + varL5 * int(cat) + varL6 * int(length))

    return render_template('predictviews.html',
                           viewPred=viewPred,
                           likePred=likePred,
                           loginmodalshow=loginmodalshow,
                           loginform=loginform,
                           modalshow=modalshow,
                           registerform=registerform)
Ejemplo n.º 22
0
def get_spend_result():
    #common ligin and signin routes
    loginmodalshow = 'close'
    loginform = LoginForm()
    if (loginform.validate_on_submit() == False and loginform.login.data):
        loginmodalshow = 'loginformmodal'
    if loginform.validate_on_submit() and loginform.login.data:
        remember = loginform.remember.data
        email = loginform.email.data
        password = loginform.password.data
        return redirect(
            url_for('users.login',
                    remember=remember,
                    email=email,
                    password=password))
    modalshow = 'close'
    registerform = RegistrationForm()
    if (registerform.validate_on_submit() == False
            and registerform.signup.data):
        modalshow = 'registerformmodal'
    if (registerform.validate_on_submit() and registerform.signup.data):
        username = registerform.username.data
        email = registerform.email.data
        password = registerform.password.data
        return redirect(
            url_for('users.register',
                    username=username,
                    email=email,
                    password=password))
    ################################

    prediction = AdPrediction()
    best_prediction = BestSolutions()
    prev_clicks = int(request.args.get('clicks'))
    day = request.args.get('weekday')
    gender = request.args.get('gender')
    txt = request.args.get('adText')
    startAge = int(request.args.get('minAge'))
    endAge = int(request.args.get('maxAge'))
    adSpends = float(request.args.get('adSpends'))  #usd
    ad_info = {
        'day': day,
        'gender': gender,
        'text': txt,
        'minAge': startAge,
        'maxAge': endAge,
        'spends': adSpends
    }

    all = 0
    male = 0
    female = 0
    if (gender == 'M'):
        male = 1
    if (gender == 'F'):
        female = 1
    if (gender == 'A'):
        all = 1
    mon = 0
    tue = 0
    wed = 0
    thu = 0
    fri = 0
    sat = 0
    sun = 0
    if (day == 'mon'):
        mon = 1
    elif (day == 'tue'):
        tue = 1
    elif (day == 'wed'):
        wed = 1
    elif (day == 'thu'):
        thu = 1
    elif (day == 'fri'):
        fri = 1
    elif (day == 'sat'):
        sat = 1
    elif (day == 'sun'):
        sun = 1

    impressions = prediction.impressions_from_money(adSpends)

    final = {
        'mon': [mon],
        'tue': [tue],
        'wed': [wed],
        'thu': [thu],
        'fri': [fri],
        'sat': [sat],
        'sun': [sun],
        'male': [male],
        'female': [female],
        'all': [all],
        'AdTextRes': [prediction.get_ad_text_result(txt)],
        'startAge': [startAge],
        'endAge': [endAge],
        'AdImpressions': [impressions],
        'AdSpends': [adSpends]
    }

    bestSolutions = BestSolutions()
    spend_result = bestSolutions.getBestSpend(final, prediction, prev_clicks)

    #### ad form ###
    adform = AdForm()
    adpredict_model = 'close'
    if (adform.validate_on_submit() == False and adform.submit.data):
        adpredict_model = 'adpredictmodel'
    if adform.validate_on_submit() and adform.submit.data:
        gender = adform.gender.data
        adText = adform.adText.data
        weekday = adform.weekday.data
        minAge = adform.minAge.data
        maxAge = adform.maxAge.data
        adSpends = adform.adSpends.data
        return redirect(
            url_for('facebook.fbAdClicksPredict',
                    gender=gender,
                    adText=adText,
                    weekday=weekday,
                    minAge=minAge,
                    maxAge=maxAge,
                    adSpends=adSpends))

### handle bot detection
    botform = FbBotForm()
    botdetection_model = 'close'
    if (botform.validate_on_submit() == False and botform.submit.data):
        botdetection_model = 'botdetectionmodel'
    if botform.validate_on_submit() and botform.submit.data:
        link = botform.link.data
        return redirect(url_for('facebook.bot', link=link))

    return render_template('facebook_ad_display_spend.html',
                           adform=adform,
                           ad_info=ad_info,
                           botform=botform,
                           registerform=registerform,
                           modalshow=modalshow,
                           loginform=loginform,
                           loginmodalshow=loginmodalshow,
                           spend_result=spend_result,
                           clicks=prev_clicks)
Ejemplo n.º 23
0
def user_details(name):
    try:
        loginmodalshow = 'close'
        loginform = LoginForm()
        if (loginform.validate_on_submit() == False and loginform.login.data):
            loginmodalshow = 'loginformmodal'
        if loginform.validate_on_submit() and loginform.login.data:
            remember = loginform.remember.data
            email = loginform.email.data
            password = loginform.password.data
            return redirect(
                url_for('users.login',
                        remember=remember,
                        email=email,
                        password=password))
        modalshow = 'close'
        registerform = RegistrationForm()
        if (registerform.validate_on_submit() == False
                and registerform.signup.data):
            modalshow = 'registerformmodal'
        if registerform.validate_on_submit() and registerform.signup.data:
            username = registerform.username.data
            email = registerform.email.data
            password = registerform.password.data
            return redirect(
                url_for('users.register',
                        username=username,
                        email=email,
                        password=password))
        twitter_client = TwitterClient()
        tweet_analyzer = TweetAnalyzer()
        user = twitter_client.get_user(name)
        tweets = twitter_client.get_tweets_of_a_user(name, 100)
        replies = 0
        mentions = 0
        hashtags = 0
        retweets = 0
        links = 0
        medias = 0
        zero = 0
        one = 0
        two = 0
        three = 0
        four = 0
        five = 0
        six = 0
        seven = 0
        eight = 0
        nine = 0
        ten = 0
        eleven = 0
        twelve = 0
        thirteen = 0
        fourteen = 0
        fifteen = 0
        sixteen = 0
        seventeen = 0
        eighteen = 0
        nineteen = 0
        twenty = 0
        twentyone = 0
        twentytwo = 0
        twentythree = 0
        ids = []
        favourites = []
        retweetscount = []
        for tweet in tweets:
            if (len(tweet.entities['hashtags']) > 0):
                hashtags += 1
            if (len(tweet.entities['user_mentions']) > 0):
                mentions += 1
            if (len(tweet.entities['urls']) > 0):
                links += 1
            if ('media' in tweet.entities):
                if (len(tweet.entities['media']) > 0):
                    medias += 1
            if (hasattr(tweet, 'retweeted_status')):
                retweets += 1
            if (tweet.in_reply_to_status_id != None):
                replies += 1
            if (tweet.created_at.hour == 0):
                zero += 1
            if (tweet.created_at.hour == 1):
                one += 1
            if (tweet.created_at.hour == 2):
                two += 1
            if (tweet.created_at.hour == 3):
                three += 1
            if (tweet.created_at.hour == 4):
                four += 1
            if (tweet.created_at.hour == 5):
                five += 1
            if (tweet.created_at.hour == 6):
                six += 1
            if (tweet.created_at.hour == 7):
                seven += 1
            if (tweet.created_at.hour == 8):
                eight += 1
            if (tweet.created_at.hour == 9):
                nine += 1
            if (tweet.created_at.hour == 10):
                ten += 1
            if (tweet.created_at.hour == 11):
                eleven += 1
            if (tweet.created_at.hour == 12):
                twelve += 1
            if (tweet.created_at.hour == 13):
                thirteen += 1
            if (tweet.created_at.hour == 14):
                fourteen += 1
            if (tweet.created_at.hour == 15):
                fifteen += 1
            if (tweet.created_at.hour == 16):
                sixteen += 1
            if (tweet.created_at.hour == 17):
                seventeen += 1
            if (tweet.created_at.hour == 18):
                eighteen += 1
            if (tweet.created_at.hour == 19):
                nineteen += 1
            if (tweet.created_at.hour == 20):
                twenty += 1
            if (tweet.created_at.hour == 21):
                twentyone += 1
            if (tweet.created_at.hour == 22):
                twentytwo += 1
            if (tweet.created_at.hour == 23):
                twentythree += 1
            ids.append(tweet.id)
            favourites.append(tweet.favorite_count)
            retweetscount.append(tweet.retweet_count)
        tweetsdata = {
            "hashtags": hashtags,
            "mentions": mentions,
            "links": links,
            "medias": medias,
            "retweets": retweets,
            "replies": replies
        }
        graphdata = {
            "0": zero,
            "1": one,
            "2": two,
            "3": three,
            "4": four,
            "5": five,
            "6": six,
            "7": seven,
            "8": eight,
            "9": nine,
            "10": ten,
            "11": eleven,
            "12": twelve,
            "13": thirteen,
            "14": fourteen,
            "15": fifteen,
            "16": sixteen,
            "17": seventeen,
            "18": eighteen,
            "19": nineteen,
            "20": twenty,
            "21": twentyone,
            "22": twentytwo,
            "23": twentythree
        }
        verified = 'NOTVERIFIED'
        badge = 'badge-danger'
        if (user.verified):
            verified = 'VERIFIED'
            badge = 'badge-success'

        return render_template('user_details.html',
                               user=user,
                               registerform=registerform,
                               modalshow=modalshow,
                               loginform=loginform,
                               loginmodalshow=loginmodalshow,
                               tweetsdata=tweetsdata,
                               verified=verified,
                               badge=badge,
                               graphdata=graphdata,
                               ids=ids,
                               favourites=favourites,
                               retweetscount=retweetscount)
    except:
        flash(
            'Something went Wrong. Please check whether enterd details are correct',
            'warning')
        return redirect(url_for('main.twitter'))
Ejemplo n.º 24
0
def hashtag_tweets(hashtag):
    loginmodalshow = 'close'
    loginform = LoginForm()
    if (loginform.validate_on_submit() == False and loginform.login.data):
        loginmodalshow = 'loginformmodal'
    if loginform.validate_on_submit() and loginform.login.data:
        remember = loginform.remember.data
        email = loginform.email.data
        password = loginform.password.data
        return redirect(
            url_for('users.login',
                    remember=remember,
                    email=email,
                    password=password))
    modalshow = 'close'
    registerform = RegistrationForm()
    if (registerform.validate_on_submit() == False
            and registerform.signup.data):
        modalshow = 'registerformmodal'
    if registerform.validate_on_submit() and registerform.signup.data:
        username = registerform.username.data
        email = registerform.email.data
        password = registerform.password.data
        return redirect(
            url_for('users.register',
                    username=username,
                    email=email,
                    password=password))
    hasht = '#' + hashtag
    twitter_client = TwitterClient()
    tweets = twitter_client.get_hashtag_tweets(hasht, 'mixed', 100)
    count = len(tweets)
    hashtag_analyzer = HashtagAnalyzer()
    hourdata = hashtag_analyzer.divide_tweets_according_to_hours(tweets)
    monthdata = hashtag_analyzer.divide_tweets_according_to_months(tweets)
    sentimentdata = hashtag_analyzer.divide_tweets_according_to_sentiment(
        tweets)
    user_mentions = hashtag_analyzer.get_user_mentions(tweets)
    hashtagslist = hashtag_analyzer.get_user_hashtags(tweets)
    userslist = hashtag_analyzer.get_users(tweets)
    mentionslength = len(user_mentions)
    hashtagslength = len(hashtagslist)
    userslength = len(userslist)
    while True:
        if (len(userslist) < 15):
            userslist.append(['', 0])
        if (len(userslist) >= 15):
            break
    while True:
        if (len(hashtagslist) < 15):
            hashtagslist.append(['', 0])
        if (len(hashtagslist) >= 15):
            break
    while True:
        if (len(user_mentions) < 15):
            user_mentions.append(['', 0])
        if (len(user_mentions) >= 15):
            break
    return render_template('hashtag.html',
                           hashtag=hashtag,
                           count=count,
                           mentionslength=mentionslength,
                           userslength=userslength,
                           hashtagslength=hashtagslength,
                           hourdata=hourdata,
                           monthdata=monthdata,
                           sentimentdata=sentimentdata,
                           user_mentions=user_mentions,
                           hashtagslist=hashtagslist,
                           userslist=userslist,
                           registerform=registerform,
                           modalshow=modalshow,
                           loginform=loginform,
                           loginmodalshow=loginmodalshow)
Ejemplo n.º 25
0
def facebook():
    loginmodalshow = 'close'
    loginform = LoginForm()
    if (loginform.validate_on_submit() == False and loginform.login.data):
        loginmodalshow = 'loginformmodal'
    if loginform.validate_on_submit() and loginform.login.data:
        remember = loginform.remember.data
        email = loginform.email.data
        password = loginform.password.data
        return redirect(
            url_for('users.login',
                    remember=remember,
                    email=email,
                    password=password))
    modalshow = 'close'
    registerform = RegistrationForm()
    if (registerform.validate_on_submit() == False
            and registerform.signup.data):
        modalshow = 'registerformmodal'
    if registerform.validate_on_submit() and registerform.signup.data:
        username = registerform.username.data
        email = registerform.email.data
        password = registerform.password.data
        return redirect(
            url_for('users.register',
                    username=username,
                    email=email,
                    password=password))

    #### handle facebook advertisements
    adform = AdForm()
    adpredict_model = 'close'
    if (adform.validate_on_submit() == False and adform.submit.data):
        adpredict_model = 'adpredictmodel'
    if adform.validate_on_submit() and adform.submit.data:
        gender = adform.gender.data
        adText = adform.adText.data
        weekday = adform.weekday.data
        minAge = adform.minAge.data
        maxAge = adform.maxAge.data
        adSpends = adform.adSpends.data
        return redirect(
            url_for('facebook.fbAdClicksPredict',
                    gender=gender,
                    adText=adText,
                    weekday=weekday,
                    minAge=minAge,
                    maxAge=maxAge,
                    adSpends=adSpends))

    ### handle senetiments
    # sentiform=SentimentForm()
    # sentiment_model='close'
    # if(sentiform.validate_on_submit()==False and sentiform.submit.data):
    # 	sentiment_model='sentimentmodel'
    # if sentiform.validate_on_submit() and sentiform.submit.data:
    # 	file_up = sentiform.upload
    # 	return redirect(url_for('facebook.sentiment',file_up=file_up))

    ### handle bot detection
    botform = FbBotForm()
    botdetection_model = 'close'
    if (botform.validate_on_submit() == False and botform.submit.data):
        botdetection_model = 'botdetectionmodel'
    if botform.validate_on_submit() and botform.submit.data:
        link = botform.link.data
        return redirect(url_for('facebook.bot', link=link))

    return render_template('facebook.html',
                           adform=adform,
                           botform=botform,
                           title='Facebook',
                           registerform=registerform,
                           modalshow=modalshow,
                           loginform=loginform,
                           loginmodalshow=loginmodalshow,
                           adpredict_model=adpredict_model)