File size: 7,131 Bytes
c3bd0c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c69946
c3bd0c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import streamlit as st
import pandas as pd
from PIL import Image
import json
from process_predict import process_predict
import re
# Enter your keys/secrets as strings in the following fields
# authorization tokens
credentials = {}
credentials['CONSUMER_KEY'] = 'XV2kS4M1OmganL2zZU0q8Kyxh'
credentials['CONSUMER_SECRET'] = 'PvjekJXnI304fE2En3cmYuftP7yOXH0xiANsWOsW1nUpbwV4j7'
credentials['ACCESS_TOKEN'] = '152569292-Uw6KPJqudtctiYjpR1GEWOMYMKGc2DhczLiZq4Q4'
credentials['ACCESS_SECRET'] = 'Muv9NC0JhKiskMqt7hO7XNbCZPRBOAOtADNaAN8xeBQ1a'

# Save the credentials object to file
with open("twitter_credentials.json", "w") as file:
    json.dump(credentials, file)
from twython import Twython
import json
# Load credentials from json file
with open("twitter_credentials.json", "r") as file:
    creds = json.load(file)
# Instantiate an object
python_tweets = Twython(creds['CONSUMER_KEY'], creds['CONSUMER_SECRET'])


# DB Management
import sqlite3 
conn = sqlite3.connect('data.db')
c = conn.cursor()

# DB  Functions
def create_usertable():
    c.execute('CREATE TABLE IF NOT EXISTS userstable(FirstName TEXT,LastName TEXT,Mobile TEXT,Email TEXT,password TEXT,Cpassword TEXT)')
def add_userdata(FirstName,LastName,Mobile,Email,password,Cpassword):
    c.execute('INSERT INTO userstable(FirstName,LastName,Mobile,Email,password,Cpassword) VALUES (?,?,?,?,?,?)',(FirstName,LastName,Mobile,Email,password,Cpassword))
    conn.commit()
def login_user(Email,password):
    c.execute('SELECT * FROM userstable WHERE Email =? AND password = ?',(Email,password))
    data = c.fetchall()
    return data
def view_all_users():
	c.execute('SELECT * FROM userstable')
	data = c.fetchall()
	return data
def delete_user(Email):
    c.execute("DELETE FROM userstable WHERE Email="+"'"+Email+"'")
    conn.commit()




def main():
    st.title("Welcome To Crime User Prediction")
    menu = ["Home","Login","SignUp"]
    choice = st.sidebar.selectbox("Menu",menu)

    if choice == "Home":
        original_title="<p style='text-align: center;'>Twitter is used extensively in the United States as well as globally, creating many opportunities to augment decision support systems with Twitter-driven predictive analytics. Twitter is an ideal data source for decision support: its users, who number in the millions, publicly discuss events, emotions, and innumerable other topics; its content is authored and distributed in real time at no charge; and individual messages (also known as tweets) are often tagged with precise spatial and temporal coordinates. This article presents research investigating the use of spatiotemporally tagged tweets for crime prediction.</p>"
        image = Image.open('flow.jpg')
        st.image(image)
        st.markdown(original_title, unsafe_allow_html=True)
    elif choice == "Login":
        st.subheader("Login Section")
        Email = st.sidebar.text_input("Email")
        password = st.sidebar.text_input("Password",type='password')
        if st.sidebar.checkbox("Login"):
            #Validation
            regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
            if re.fullmatch(regex, Email):
                create_usertable()
                if Email=='a@a.com' and password=='123':
                    st.success("Logged In as {}".format("Admin"))
                    Email=st.text_input("Delete Email")
                    if st.button('Delete'):
                        delete_user(Email)
                    user_result = view_all_users()
                    clean_db = pd.DataFrame(user_result,columns=["FirstName","LastName","Mobile","Email","password","Cpassword"])
                    st.dataframe(clean_db)
                else:
                    result = login_user(Email,password)
                    if result:
                        location=['Gujarat','UP','Maharastra','Delhi']
                        choice = st.selectbox("Select Location",location)
                        if choice=='Gujarat':
                            geocode = '28.6517178,77.2219388,1000mi' # latitude,longitude,distance(mi/km)
                        if choice=='UP':
                            geocode = '28.6517178,77.2219388,1000mi' # latitude,longitude,distance(mi/km)
                        if choice=='Maharastra':
                            geocode = '28.6517178,77.2219388,1000mi' # latitude,longitude,distance(mi/km)
                        if choice=='Delhi':
                            geocode = '28.6517178,77.2219388,1000mi' # latitude,longitude,distance(mi/km)
                        texts=str(st.text_input("Enter Keyword with AND and OR operator"))
                        keywords=texts+" -filter:retweets"
                        query = {'q': keywords,
                                'count': 100,
                                'lang': 'en',
                                'geocode': geocode,
                                }
                        if st.button('Retrive Tweets'):
                            # Search tweets
                            dict_ = {'user': [], 'date': [], 'text': [], 'user_loc': []}
                            for status in python_tweets.search(**query)['statuses']:
                                dict_['user'].append(status['user']['screen_name'])
                                dict_['date'].append(status['created_at'])
                                dict_['text'].append(status['text'])
                                dict_['user_loc'].append(status['user']['location'])
                            # Structure data in a pandas DataFrame for easier manipulation
                            df = pd.DataFrame(dict_)
                            st.dataframe(df)
                            df1=process_predict(df)
                        if st.button("Process and Predict"):
                            df1=pd.read_csv("tweets.csv")
                            st.dataframe(df1)   
                    else:
                        st.warning("Incorrect Email/Password")
            else:
                st.warning("Not Valid Email")
                
    elif choice == "SignUp":
        FirstName = st.text_input("Firstname")
        LastName = st.text_input("Lastname")
        Mobile = st.text_input("Mobile")
        Email = st.text_input("Email")
        new_password = st.text_input("Password",type='password')
        Cpassword = st.text_input("Confirm Password",type='password')
        if st.button("Signup"):
            pattern=re.compile("(0|91)?[7-9][0-9]{9}")
            regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
            if (pattern.match(Mobile)):
                if re.fullmatch(regex, Email):
                    create_usertable()
                    add_userdata(FirstName,LastName,Mobile,Email,new_password,Cpassword)
                    st.success("You have successfully created a valid Account")
                    st.info("Go to Login Menu to login")
                else:
                    st.warning("Not Valid Email")
            else:
                st.warning("Not Valid Mobile Number")
                    
           
if __name__ == '__main__':
    main()