narekob1998 commited on
Commit
9b3f058
1 Parent(s): 368c618

Creat app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -0
app.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PyPDF2 import PdfReader
3
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
4
+ import os
5
+ import io
6
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings
7
+ import google.generativeai as genai
8
+ from langchain.vectorstores import FAISS
9
+ from langchain_google_genai import ChatGoogleGenerativeAI
10
+ from langchain.chains.question_answering import load_qa_chain
11
+ from langchain.prompts import PromptTemplate
12
+ from dotenv import load_dotenv
13
+ from langchain import HuggingFaceHub
14
+ import boto3
15
+ from botocore.config import Config
16
+ from st_files_connection import FilesConnection
17
+ load_dotenv()
18
+ os.getenv("GOOGLE_API_KEY")
19
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
20
+
21
+ bucket_name = "chatbot-resume"
22
+
23
+ def get_pdf_text_from_s3(bucket_name, pdf_keys):
24
+ s3 = boto3.client('s3', config=Config(signature_version='s3v4'))
25
+ text = ""
26
+ for pdf_key in pdf_keys:
27
+ response = s3.get_object(Bucket=bucket_name, Key=pdf_key)
28
+ pdf_data = response['Body'].read()
29
+ pdf_file = io.BytesIO(pdf_data)
30
+ pdf_reader = PdfReader(pdf_file)
31
+ for page in pdf_reader.pages:
32
+ text += page.extract_text()
33
+ return text
34
+
35
+ def get_text_chunks(text):
36
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
37
+ chunks = text_splitter.split_text(text)
38
+ return chunks
39
+
40
+ def get_vector_store(text_chunks):
41
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
42
+ vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
43
+ vector_store.save_local("faiss_index")
44
+
45
+ def get_conversational_chain():
46
+ prompt_template = """
47
+ Answer the question as detailed as possible from the provided context, make sure to provide all the details, if the answer is not in
48
+ provided context just say, "answer is not available in the context", don't provide the wrong answer, try to convince that skillset is amazing and promising as this is intended for recruiters, also the number format mm/yyyy - mm/yyyy
49
+ is for start and end date of university or work, BS refers to Bachelors degree.\n\n
50
+ Context:\n {context}?\n
51
+ Question: \n{question}\n
52
+
53
+ Answer:
54
+ """
55
+ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
56
+ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
57
+ chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
58
+ return chain
59
+
60
+ def user_input(user_question):
61
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
62
+ new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
63
+ docs = new_db.similarity_search(user_question)
64
+ chain = get_conversational_chain()
65
+ response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
66
+ st.write("Reply: ", response["output_text"])
67
+
68
+ def main():
69
+ st.set_page_config("Chat PDF")
70
+ st.header("Chat with Narek's Resume(Google Gemini)")
71
+ conn = st.connection('s3', type=FilesConnection)
72
+ user_question = st.text_input("Ask a Question from the PDF Files")
73
+
74
+ if user_question:
75
+ pdf_keys = [] # Initialize an empty list to store PDF file keys
76
+ s3 = boto3.client('s3')
77
+ paginator = s3.get_paginator('list_objects_v2')
78
+ for result in paginator.paginate(Bucket=bucket_name):
79
+ if 'Contents' in result:
80
+ for item in result['Contents']:
81
+ if item['Key'].endswith('.pdf'): # Check if the object is a PDF file
82
+ pdf_keys.append(item['Key']) # Add the PDF file key to the list
83
+ raw_text = get_pdf_text_from_s3(bucket_name, pdf_keys)
84
+ text_chunks = get_text_chunks(raw_text)
85
+ get_vector_store(text_chunks)
86
+ user_input(user_question)
87
+
88
+ with st.sidebar:
89
+ st.title("Menu:")
90
+ st.write("Please wait while PDF files are fetched from S3...")
91
+
92
+ if __name__ == "__main__":
93
+ main()