moazzamdev commited on
Commit
19aa68f
·
1 Parent(s): 0574b85

Upload 5 files

Browse files
Files changed (5) hide show
  1. app.py +117 -0
  2. login.py +46 -0
  3. query.py +107 -0
  4. signup.py +22 -0
  5. user_credentials.db +0 -0
app.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from signup import signup
3
+ from login import login
4
+ from query import run_query_app
5
+ from streamlit_option_menu import option_menu
6
+
7
+ # this the fucntion to show the greater value
8
+
9
+
10
+ def myFUnc():
11
+ print('moazzam riaz')
12
+ i = 1
13
+ if i == 0:
14
+ print('the number is geater than the value')
15
+
16
+ else:
17
+ print('the number is not grate')
18
+
19
+ # this the recursion function to calculate the factorial
20
+
21
+
22
+ def thiFunc(n):
23
+
24
+ input('enter to calculate factorial', n)
25
+ if n == 0 or n == 1:
26
+ return 1
27
+
28
+ else:
29
+ return n * thiFunc(n - 1)
30
+
31
+ # this the function to including inheritaNCE and method overloading polymorphism
32
+
33
+
34
+ class Animal:
35
+
36
+ def sound():
37
+ print('aniaml sound')
38
+
39
+
40
+ class Dog(Animal):
41
+
42
+ def sound():
43
+ print('boww bpoww')
44
+
45
+
46
+ # this class is with a constructor which will be called automaticlly when the object is created
47
+ class Cat(Animal):
48
+
49
+ def sound():
50
+ print('meoww meoww')
51
+
52
+ def __init__(self, a, b):
53
+
54
+ self.a = a,
55
+ self.b = b,
56
+
57
+
58
+ '''
59
+ the concecpts of oop
60
+ inheritance--this concept is about the classes like we have class animanls now it will have sub classes like cat or dog this is inheritance(single level, multi level, hybrid)
61
+ polymorphism--two methods one is method overloading which means that the function name and parameters are similar other one is method overloading in which the function name is similar but parameters are different
62
+ encapsulation--the hiddin of data which can not be accessed from outside the class three types private, public and protected
63
+ classes--the blueprint containing all the infomartion of the particular rela world thing contain functuion or methods
64
+ abstraction--the function which do not have any return value or dont contain any info in the function all the implementstion is done from the parent or subclass
65
+ recursion--the recursion is all about that we created a function and calling it inside the function
66
+ arrays--the arrays are that contain lists or any info like numbers 1 -100 this can of three types 1d, 2d and 3d everyone ahve it's pwn functinality
67
+ objects--the objects are the instance of classes to call the fnctions
68
+ these concept are from oop which can be used from any proraming lang
69
+ where as python is a dynamic language
70
+ so there is many the langugae= uncluding pythobn etc
71
+ '''
72
+ # my name is moazzam riaz the student of university of lahore
73
+
74
+
75
+ def main():
76
+
77
+ st.title("Document Query System")
78
+
79
+ # Step 1: Initialize session state variables
80
+ if 'username' not in st.session_state:
81
+ st.session_state['username'] = None
82
+ if 'login_successful' not in st.session_state:
83
+ st.session_state['login_successful'] = False
84
+
85
+ # Step 2: Check if user is logged in
86
+ if st.session_state['username'] is None:
87
+ # User is not logged in, display login and signup options
88
+ selection = option_menu(
89
+ menu_title="Main Menu",
90
+ options=["Login", "Signup"],
91
+ icons=["person", "person"],
92
+ menu_icon="cast",
93
+ default_index=1
94
+ )
95
+
96
+ if selection == "Login":
97
+ st.session_state['username'] = login()
98
+ if st.session_state['username']:
99
+ st.session_state['login_successful'] = True
100
+ elif selection == "Signup":
101
+ signup()
102
+
103
+ # Step 3: Check if user is logged in successfully
104
+ if 'login_successful' in st.session_state and st.session_state['login_successful']:
105
+ # User is logged in, display welcome message and query page
106
+ if 'username' in st.session_state and st.session_state['username']:
107
+ st.subheader(f"Welcome, {st.session_state['username']}!")
108
+ run_query_app(st.session_state['username'])
109
+
110
+
111
+ if st.sidebar.button("Logout"):
112
+ st.session_state['username'] = None
113
+ st.session_state['login_successful'] = False
114
+ st.empty() # Clear the contents of the page
115
+
116
+ if __name__ == '__main__':
117
+ main()
login.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import hashlib
3
+ import sqlite3
4
+ from query import run_query_app
5
+
6
+ def create_user_table():
7
+ conn = sqlite3.connect('user_credentials.db')
8
+ c = conn.cursor()
9
+ c.execute('''
10
+ CREATE TABLE IF NOT EXISTS users (
11
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
12
+ email TEXT UNIQUE,
13
+ username TEXT,
14
+ password TEXT
15
+ )
16
+ ''')
17
+ conn.commit()
18
+ conn.close()
19
+
20
+
21
+
22
+ def login():
23
+ st.subheader("Login")
24
+
25
+ email = st.text_input("Email")
26
+ password = st.text_input("Password", type="password")
27
+ submit_button = st.button("Login")
28
+
29
+ if submit_button:
30
+ hashed_password = hashlib.sha256(password.encode()).hexdigest()
31
+ conn = sqlite3.connect('user_credentials.db')
32
+ c = conn.cursor()
33
+ c.execute("SELECT * FROM users WHERE email = ? AND password = ?", (email, hashed_password))
34
+ user = c.fetchone()
35
+ conn.close()
36
+
37
+ if user:
38
+ st.success("Login successful!")
39
+ return user[1] # Return the username
40
+ else:
41
+ st.error("Invalid email or password.")
42
+ return None
43
+
44
+
45
+
46
+
query.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import openai
4
+ import PyPDF2
5
+ from langchain.embeddings import OpenAIEmbeddings
6
+ from langchain.vectorstores import Chroma
7
+ from langchain import OpenAI
8
+ from langchain import VectorDBQA
9
+ from langchain.document_loaders import UnstructuredFileLoader, UnstructuredPDFLoader
10
+ from langchain.text_splitter import CharacterTextSplitter
11
+ import nltk
12
+ from streamlit_chat import message
13
+
14
+ nltk.download("punkt")
15
+
16
+
17
+ def run_query_app(username):
18
+ openai_api_key = st.sidebar.text_input("OpenAI API Key", key="openai_api_key_input", type="password")
19
+
20
+ uploaded_file = st.file_uploader("Upload a file", type=['txt', 'pdf'], key="file_uploader")
21
+ if uploaded_file:
22
+ # Save the uploaded file
23
+ file_path = os.path.join('./uploaded_files', uploaded_file.name)
24
+ with open(file_path, "wb") as f:
25
+ f.write(uploaded_file.read())
26
+
27
+ # Initialize OpenAIEmbeddings
28
+
29
+ os.environ['OPENAI_API_KEY'] = openai_api_key
30
+
31
+ # Initialize OpenAIEmbeddings
32
+ embeddings = OpenAIEmbeddings(openai_api_key=os.environ['OPENAI_API_KEY'])
33
+
34
+ # Load the file as document
35
+ _, ext = os.path.splitext(file_path)
36
+ if ext == '.txt':
37
+ loader = UnstructuredFileLoader(file_path)
38
+ elif ext == '.pdf':
39
+ loader = UnstructuredPDFLoader(file_path)
40
+ else:
41
+ st.write("Unsupported file format.")
42
+ return
43
+
44
+ documents = loader.load()
45
+
46
+ # Split the documents into texts
47
+ text_splitter = CharacterTextSplitter(chunk_size=800, chunk_overlap=0)
48
+ texts = text_splitter.split_documents(documents)
49
+
50
+ # Create Chroma vectorstore from documents
51
+ doc_search = Chroma.from_documents(texts, embeddings)
52
+
53
+ # Initialize VectorDBQA
54
+ chain = VectorDBQA.from_chain_type(llm=OpenAI(), chain_type="stuff", vectorstore=doc_search)
55
+
56
+ if 'messages' not in st.session_state:
57
+ st.session_state['messages'] = []
58
+
59
+ if 'past' not in st.session_state:
60
+ st.session_state['past'] = []
61
+
62
+ if 'generated' not in st.session_state:
63
+ st.session_state['generated'] = []
64
+
65
+ def update_chat(messages, sender, text):
66
+ message = {'sender': sender, 'text': text}
67
+ messages.append(message)
68
+ return messages
69
+
70
+ def get_response(chain, messages):
71
+ input_text = [m['text'] for m in messages if m['sender'] == 'user']
72
+ result = chain.run(input_text[-1])
73
+ return result
74
+
75
+ def get_text():
76
+ input_text = st.text_input("You: ", key="input")
77
+ return input_text
78
+
79
+ query = get_text()
80
+ user_input = query
81
+
82
+ if st.button("Run Query"):
83
+ with st.spinner("Generating..."):
84
+ messages = st.session_state.get('messages', [])
85
+ messages = update_chat(messages, "user", query)
86
+ response = get_response(chain, messages)
87
+ messages = update_chat(messages, "assistant", response)
88
+ st.session_state['messages'] = messages
89
+ st.session_state['past'].append(query)
90
+ st.session_state['generated'].append(response)
91
+ if uploaded_file is not None:
92
+ message(f"You are chatting with {uploaded_file.name}. Ask anything about it?")
93
+ if st.session_state['generated']:
94
+
95
+ for i in range(len(st.session_state['generated']) - 1, -1, -1):
96
+ message(st.session_state['past'][i], is_user=True, key=str(i) + '_user')
97
+ message(st.session_state['generated'][i], key=str(i))
98
+
99
+ with st.expander("Show Messages"):
100
+ for i, msg in enumerate(st.session_state['messages']):
101
+ if msg['sender'] == 'user':
102
+ message("User", msg['text'], key=f"user_{i}")
103
+ else:
104
+ message("Assistant", msg['text'], key=f"assistant_{i}")
105
+
106
+ if __name__ == '__main__':
107
+ run_query_app()
signup.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import hashlib
3
+ import sqlite3
4
+
5
+ def signup():
6
+ st.subheader("Signup")
7
+ email = st.text_input("Email")
8
+ username = st.text_input("Username")
9
+ password = st.text_input("Password", type="password")
10
+
11
+ if len(password) < 8:
12
+ st.warning("Password must be at least 8 characters long.")
13
+ return
14
+
15
+ if st.button("Signup"):
16
+ hashed_password = hashlib.sha256(password.encode()).hexdigest()
17
+ conn = sqlite3.connect('user_credentials.db')
18
+ c = conn.cursor()
19
+ c.execute("INSERT INTO users (email, username, password) VALUES (?, ?, ?)", (email, username, hashed_password))
20
+ conn.commit()
21
+ conn.close()
22
+ st.success("Signup successful! Please login.")
user_credentials.db ADDED
Binary file (12.3 kB). View file