JustKiddo commited on
Commit
85c933f
Β·
verified Β·
1 Parent(s): 75caf1e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -0
app.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import PyPDF2
3
+ import io
4
+ from typing import List, Dict
5
+ from groq import Groq
6
+
7
+ # Page configuration and styling
8
+ st.set_page_config(
9
+ page_title="PDF AI Chat Assistant",
10
+ page_icon="πŸ“„",
11
+ layout="wide"
12
+ )
13
+
14
+ class PDFChatAssistant:
15
+ def __init__(self):
16
+ # Initialize session state variables
17
+ if 'chat_history' not in st.session_state:
18
+ st.session_state.chat_history = []
19
+ if 'uploaded_pdf' not in st.session_state:
20
+ st.session_state.uploaded_pdf = None
21
+ if 'pdf_text' not in st.session_state:
22
+ st.session_state.pdf_text = ""
23
+
24
+ def extract_pdf_text(self, pdf_file) -> str:
25
+ """
26
+ Extract text from uploaded PDF file
27
+ """
28
+ try:
29
+ pdf_reader = PyPDF2.PdfReader(pdf_file)
30
+ text = ""
31
+ for page in pdf_reader.pages:
32
+ text += page.extract_text() + "\n\n"
33
+ return text
34
+ except Exception as e:
35
+ st.error(f"Error extracting PDF text: {e}")
36
+ return ""
37
+
38
+ def create_groq_client(self) -> Groq:
39
+ """
40
+ Create Groq client with API key
41
+ """
42
+ client = Groq(api_key=st.secrets["GROQ_API_KEY"])
43
+ return client
44
+
45
+ def generate_ai_response(self, client: Groq, context: str, user_query: str) -> str:
46
+ """
47
+ Generate AI response using Groq API
48
+ """
49
+ try:
50
+ chat_completion = client.chat.completions.create(
51
+ messages=[
52
+ {
53
+ "role": "system",
54
+ "content": f"You are a helpful PDF assistant. Use the following PDF context to answer questions:\n\n{context}"
55
+ },
56
+ {
57
+ "role": "user",
58
+ "content": user_query
59
+ }
60
+ ],
61
+ model="llama3-8b-8192"
62
+ )
63
+ return chat_completion.choices[0].message.content
64
+ except Exception as e:
65
+ st.error(f"Error generating AI response: {e}")
66
+ return "Sorry, I couldn't generate a response."
67
+
68
+ def display_chat_interface(self):
69
+ """
70
+ Main chat interface with PDF upload and interaction
71
+ """
72
+ st.title("πŸ“„ PDF AI Chat Assistant")
73
+
74
+ # Sidebar for PDF upload and context management
75
+ with st.sidebar:
76
+ st.header("PDF Management")
77
+ uploaded_file = st.file_uploader("Upload PDF", type=['pdf'])
78
+
79
+ if uploaded_file is not None:
80
+ st.session_state.uploaded_pdf = uploaded_file
81
+ with st.spinner('Extracting text from PDF...'):
82
+ st.session_state.pdf_text = self.extract_pdf_text(uploaded_file)
83
+ st.success("PDF text extracted successfully!")
84
+
85
+ # Context actions
86
+ col1, col2 = st.columns(2)
87
+ with col1:
88
+ if st.button("Summarize PDF", key="summarize_btn"):
89
+ st.session_state.chat_history.append({
90
+ "role": "user",
91
+ "content": "Provide a comprehensive summary of this PDF"
92
+ })
93
+
94
+ with col2:
95
+ if st.button("Key Points", key="key_points_btn"):
96
+ st.session_state.chat_history.append({
97
+ "role": "user",
98
+ "content": "Extract the most important key points from this PDF"
99
+ })
100
+
101
+ # Main chat area
102
+ st.header("Chat with Your PDF")
103
+
104
+ # Display chat history
105
+ for message in st.session_state.chat_history:
106
+ with st.chat_message(message['role']):
107
+ st.markdown(message['content'])
108
+
109
+ # Groq Client setup
110
+ client = self.create_groq_client()
111
+
112
+ # User input
113
+ if prompt := st.chat_input("Ask a question about your PDF"):
114
+ # Add user message to chat history
115
+ st.session_state.chat_history.append({
116
+ "role": "user",
117
+ "content": prompt
118
+ })
119
+
120
+ # Display user message
121
+ with st.chat_message("user"):
122
+ st.markdown(prompt)
123
+
124
+ # Generate and display AI response
125
+ if client and st.session_state.pdf_text:
126
+ with st.chat_message("assistant"):
127
+ with st.spinner('Generating response...'):
128
+ response = self.generate_ai_response(
129
+ client,
130
+ st.session_state.pdf_text,
131
+ prompt
132
+ )
133
+ st.markdown(response)
134
+
135
+ # Add AI response to chat history
136
+ st.session_state.chat_history.append({
137
+ "role": "assistant",
138
+ "content": response
139
+ })
140
+ else:
141
+ st.warning("Please upload a PDF.")
142
+
143
+ # Reset button
144
+ if st.button("Clear Chat", key="reset_btn"):
145
+ st.session_state.chat_history = []
146
+ st.experimental_rerun()
147
+
148
+ def main():
149
+ assistant = PDFChatAssistant()
150
+ assistant.display_chat_interface()
151
+
152
+ if __name__ == "__main__":
153
+ main()