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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import streamlit as st
import os
import json
from langchain.chat_models import ChatOpenAI
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.chains import RetrievalQA
from langchain.vectorstores import FAISS
from langchain.prompts.prompt import PromptTemplate
from langchain.embeddings import HuggingFaceEmbeddings
import json
import hashlib
import pdf2bib
# Initialize the storage directories if they don't exist
model_name = "intfloat/e5-large-v2"
model_kwargs = {'device': 'cpu'}
encode_kwargs = {'normalize_embeddings': False}
embeddings = HuggingFaceEmbeddings(
    model_name=model_name,
    model_kwargs=model_kwargs,
    encode_kwargs=encode_kwargs
    )

USERS_DB_FILE = 'users_db.json'

def load_users():
    if os.path.exists(USERS_DB_FILE):
        with open(USERS_DB_FILE, 'r') as file:
            return json.load(file)
    return {}

# Helper function to save users to file
def save_users(users_db):
    with open(USERS_DB_FILE, 'w') as file:
        json.dump(users_db, file, indent=4)

# Helper function to hash passwords
def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()

# Function to check if a user exists
def user_exists(username):
    users_db = load_users()
    return username in users_db

# Sign-up function
def sign_up_user(username, password):
    users_db = load_users()
    if username in users_db:
        return False, "Username already exists."
    else:
        assets_dir = os.path.join('user_assets', f'user_{username}_assets')
        users_db[username] = {
            "username": username,
            "password": hash_password(password),
            "assets_dir": assets_dir
        }
        save_users(users_db)
        # Create user's asset directory
        if not os.path.exists(assets_dir):
            os.makedirs(assets_dir)
        return True, "User created successfully."

# Load existing metadata from JSON file
def load_metadata(metadata_dir):
    metadata_path = os.path.join(metadata_dir, 'metadata.json')
    if os.path.exists(metadata_path):
        with open(metadata_path, 'r') as f:
            return json.load(f)
    return {}

def save_metadata(metadata, metadata_dir):
    metadata_path = os.path.join(metadata_dir, 'metadata.json')
    with open(metadata_path, 'w') as f:
        json.dump(metadata, f, indent=4)

#Add a new entry to the metadata
def add_metadata(file_path, title, author, year,journal, publisher, DOI,page,volume,issue):
     metadata = load_metadata(st.session_state['metadata_dir'])
     metadata_dir = st.session_state['metadata_dir']
     metadata[file_path] = {
         'title': title,
         'author': author,
         'year': year,
         'journal': journal,
         'publisher': publisher,
         'DOI': DOI,
         'page':page,
         "volume":volume,
         "issue":issue
     }
     save_metadata(metadata, metadata_dir)

def edit_metadata_of_selected_pdf(metadata):
    st.title('PDF Metadata Editor')
    
    # Use a select box for users to choose a PDF
    file_names = list(metadata.keys())
    selected_file = st.selectbox('Select a PDF file to edit metadata', file_names)
    metadata_dir = st.session_state['metadata_dir']

    # When a file is selected, show its metadata in editable form fields
    if selected_file:
        data = metadata[selected_file]
        st.subheader('Edit Metadata for Selected PDF:')
        
        # Use columns to arrange the text inputs
        col1, col2 = st.columns(2)
        
        with st.form(key=f'edit_form_{selected_file}'):
            with col1:
                edited_title = st.text_input('Title', value=data['title'])
                edited_author = st.text_input('Author', value=data['author'])
                edited_year = st.text_input('Published Year', value=data['year'], max_chars=4)
                edited_volume = st.text_input('volume', value=data['volume'])

            with col2:
                edited_journal = st.text_input('journal', value=data['journal'])
                edited_publisher = st.text_input('Publisher', value=data['publisher'])
                edited_DOI = st.text_input('DOI', value=data['DOI'])
                edited_page = st.text_input('Page', value=data['page'])
                edited_issue = st.text_input('issue', value=data['issue'])

            # Submit button for the form
            submit_button = st.form_submit_button(label='Update Metadata')

            if submit_button:
                # Update the metadata dictionary with the new values
                metadata[selected_file] = {
                    'title': edited_title,
                    'author': edited_author,
                    'year': edited_year,
                    'journal': edited_journal,
                    'publisher': edited_publisher,
                    'DOI': edited_DOI,
                    'page': edited_page,
                    'volume':edited_volume,
                    'issue':edited_issue

                }
                save_metadata(metadata,metadata_dir)  # Make sure this function properly handles the saving
                st.success('Metadata updated successfully!')
# ... [The previous code sections remain unchanged] ...

# Function to delete selected PDF and its metadata
def delete_pdf_and_metadata(metadata):
    # Use a select box for users to choose a PDF to delete
    metadata_dir = st.session_state['metadata_dir']
    #st.write(list(metadata.keys()))
    file_names = list(metadata.keys())
    if not file_names:
        st.write("No PDFs available to delete.")
        return

    selected_file_to_delete = st.selectbox('Select a PDF file to delete', file_names)
    st.write(selected_file_to_delete)
    # Button to delete the PDF and its metadata
    if st.button(f"Delete '{selected_file_to_delete}' and its metadata"):
        # Delete the PDF file
        os.remove(selected_file_to_delete)

        # Delete the metadata entry
        del metadata[selected_file_to_delete]
        save_metadata(metadata, metadata_dir)

        # Update the display
        #st.experimental_rerun()

def generate_response(input_text,openai_api_key):
    db = FAISS.load_local(st.session_state['embed_dir'], embeddings)
    docs = db.similarity_search(input_text,k=5)

    json1 = json.dumps(docs[0].metadata)
    json2 = json.dumps(docs[1].metadata)
    json3 = json.dumps(docs[2].metadata)
    json4 = json.dumps(docs[3].metadata)
    json5 = json.dumps(docs[4].metadata)
    QA_TEMPLATE = """ provide an academic answer within 100 words based on the context :"
                        {context}
                        Question: {question}

                        use metadata in the "metadata" html block to create APA style references and list them in a reference section:
                        <metadata>
                        {source1},{source2},{source3},{source4},{source5}
                        <metadata/>

                        make sure to add references

                        format the answer in markdown format

                        """
    QA_PROMPT = PromptTemplate(input_variables=["question", "context"],
                                                        partial_variables={"source1":json1, "source2":json2,
                                                       "source3":json3,"source4":json4,"source5":json5},
                                                         template=QA_TEMPLATE, )
    llm = ChatOpenAI(
                    model_name="gpt-3.5-turbo",
                    temperature=0.05,
                    max_tokens=1500, 
                    openai_api_key=openai_api_key
                )

            # Define retriever
    retriever = db.as_retriever(search_type="mmr",search_kwargs={"k": 5})

    qa_chain = RetrievalQA.from_chain_type(llm, 
                                                        retriever=retriever,
                                                        chain_type="stuff", #"stuff", "map_reduce","refine", "map_rerank"
                                                        return_source_documents=True,
                                                        verbose=True,
                                                        chain_type_kwargs={"prompt": QA_PROMPT}
                                                        )
                
    return qa_chain({'query': input_text})
#Dummy user database
def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()

# Simple user database structure
users_db = load_users()


# Login function
def login_user(username, password):
    if username in users_db and users_db[username]['password'] == hash_password(password):
        return True
    return False

# Initialize user assets directory
def init_user_assets(username):
    assets_dir = os.path.join(users_db[username]['assets_dir'])
    pdf_dir = os.path.join(assets_dir, 'pdfs')
    metadata_dir = os.path.join(assets_dir, 'metadata')
    embed_dir = os.path.join(assets_dir, 'embed')
    if not os.path.exists(pdf_dir):
        os.makedirs(pdf_dir)
    if not os.path.exists(metadata_dir):
        os.makedirs(metadata_dir)
    if not os.path.exists(embed_dir):
        os.makedirs(embed_dir)
    return assets_dir, pdf_dir, metadata_dir, embed_dir



def all_author_names(data):
    author_full_names = []
    authors_string =[]
    if not data:
        authors_string=''
# Iterate over each author in the author list
    else:
        for author in data["author"]:
            # Combine given and family names
            full_name = f"{author['family']},{author['given']}"
            author_full_names.append(full_name)

# Join the list of author names into a single string separated by commas
        authors_string = "; ".join(author_full_names)
    return authors_string
# Main App
def main():
    st.title('LLM powered paper management system')

    # New sidebar options
    if 'logged_in' not in st.session_state or not st.session_state['logged_in']:
        with st.sidebar:
            tab1, tab2 = st.tabs(["Login", "Sign-up"])
            with tab1:
                username = st.text_input("Username")
                password = st.text_input("Password", type='password')
                if st.sidebar.button("Login"):
                    if login_user(username, password):
                        st.session_state['logged_in'] = True
                        st.session_state['username'] = username
                        # Initialize user assets upon login
                        assets_dir, pdf_dir, metadata_dir, embed_dir = init_user_assets(username)
                        st.session_state['assets_dir'] = assets_dir
                        st.session_state['pdf_dir'] = pdf_dir
                        st.session_state['metadata_dir'] = metadata_dir
                        st.session_state['embed_dir'] = embed_dir
                        st.success(f"Logged in as {username}")
                    else:
                        st.error("Incorrect username or password")
            with tab2:
                new_username = st.text_input("Choose a username", key="signup_username")
                new_password = st.text_input("Choose a password", type='password', key="signup_password")
                confirm_password = st.text_input("Confirm password", type='password', key="confirm_password")
                        
                if st.button("Sign up"):
                    if new_password == confirm_password:
                                success, message = sign_up_user(new_username, new_password)
                    if success:
                                    st.success(message)
                                    #st.session_state['logged_in'] = True
                                    #st.session_state['username'] = new_username
                                    st.experimental_rerun()
                    else:
                                    st.error(message)
                else:
                                st.error("Passwords do not match.")
    if st.session_state.get('logged_in'):

                # Continue with the rest of the app
                tab1, tab2, tab3,tab4 = st.tabs(["Upload pdfs", "Manage metadata", "Embed pdfs","Retrive pdfs"])
                # PDF file upload
                with tab1:
                    uploaded_files = st.file_uploader("Choose PDF files", accept_multiple_files=True, type='pdf')
                    for uploaded_file in uploaded_files:
                        if uploaded_file is not None:
                            # Save file
                            file_path = os.path.join(st.session_state['pdf_dir'], uploaded_file.name)

                            with open(file_path, "wb") as f:
                                f.write(uploaded_file.getbuffer())
                            pdfextractdata = pdf2bib.pdf2bib(file_path)
                            #st.write(pdfextractdata)
                            pdfextractdata_metadata = {} if pdfextractdata['metadata'] is None else pdfextractdata.get('metadata', {})
                            #st.write(pdfextractdata_metadata)
                            #st.write(pdfextractdata['metadata'])
                            # Collect metadata
                            with st.form(key=uploaded_file.name):
                                st.write("Metadata for:", uploaded_file.name)
                                col1, col2, col3 = st.columns(3)
                        

                                with col1:
                                    title = st.text_input('Title', key=f'title_{uploaded_file.name}', value=pdfextractdata_metadata.get('title', ''))
                                    year = st.text_input('Published Year', key=f'year_{uploaded_file.name}', value=pdfextractdata_metadata.get('year', ''))
                                    volume = st.text_input('Volume', key=f'volume_{uploaded_file.name}', value=pdfextractdata_metadata.get('volume', ''))

                                with col2:
                                    author = st.text_input('Author', key=f'author_{uploaded_file.name}', value=all_author_names(pdfextractdata_metadata))
                                    journal = st.text_input('Journal', key=f'journal_{uploaded_file.name}', value=pdfextractdata_metadata.get('journal', ''))
                                    issue = st.text_input('Issue', key=f'issue_{uploaded_file.name}', value=pdfextractdata_metadata.get('issue', ''))

                                with col3:
                                    publisher = st.text_input('Publisher', key=f'publisher_{uploaded_file.name}', value=pdfextractdata_metadata.get('publisher', ''))
                                    DOI = st.text_input('DOI', key=f'DOI_{uploaded_file.name}', value=pdfextractdata_metadata.get('doi', ''))
                                    page = st.text_input('Pages', key=f'page_{uploaded_file.name}', value=pdfextractdata_metadata.get('page', ''))
                                submitted = st.form_submit_button('Save Metadata')
                                if submitted:
                                    add_metadata(file_path, title, author, year, journal,publisher, DOI,page,volume,issue)
                                    st.success('Metadata saved!')

                    with tab2:
                        edit_metadata_of_selected_pdf(load_metadata(st.session_state['metadata_dir']))
                        delete_pdf_and_metadata(load_metadata(st.session_state['metadata_dir']))
                    with tab3:
                        submittedDB = st.button('embed pdfs')

                        if submittedDB:
                            from langchain.document_loaders import PyPDFDirectoryLoader
                            from langchain.text_splitter import RecursiveCharacterTextSplitter
                            from langchain.docstore.document import Document
                            text_splitter = RecursiveCharacterTextSplitter(
                                # Set a really small chunk size, just to show.
                                    chunk_size = 1000,
                                    chunk_overlap  = 0,
                                    length_function = len,
                                )
                            loader = PyPDFDirectoryLoader(st.session_state['pdf_dir'])
                            
                            docs = loader.load_and_split(text_splitter=text_splitter)
                            st.write(docs[0])
                            for doc in docs:
                                source_file = doc.metadata['source']
                                metadata = load_metadata(st.session_state['metadata_dir'])
                                # Check if the source_file is in the metadata dictionary
                                if source_file in metadata:
                                    # Extract the corresponding metadata
                                    corresponding_metadata = metadata[source_file]
                                    
                                    # Update the page_content metadata with the corresponding details
                                    doc.metadata.update({
                                        "title": corresponding_metadata["title"],
                                        "author": corresponding_metadata["author"],
                                        "year": corresponding_metadata["year"],
                                        "journal": corresponding_metadata["journal"],
                                        "publisher": corresponding_metadata["publisher"],
                                        "DOI": corresponding_metadata["DOI"],
                                        "page": corresponding_metadata["page"],
                                    })
                            st.write(docs[0])



                            db = FAISS.from_documents(docs, embeddings)
                            db.save_local(st.session_state['embed_dir'])
                    with tab4:
                        # load IPCC vector database
                        

                        with st.sidebar:
                            openai_api_key = st.text_input("OpenAI API Key", type="password")
                            "[Get an OpenAI API key](https://platform.openai.com/account/api-keys)"





                        with st.form("my_form"):
                            text = st.text_area("Enter text:", "")
                            submitted = st.form_submit_button("Submit")
                            if not openai_api_key:
                                st.info("Please add your OpenAI API key to continue.")
                            elif submitted:
                                result = generate_response(text, openai_api_key)
                                st.markdown(result["result"])
                                #st.markdown(result["source_documents"])

        # Here you would implement the logic for user sign up
        # ...

# Function calls to hash the password (just for demonstration, remove in production)
# make_hashes("admin")

if __name__ == '__main__':
    main()