Sayandip commited on
Commit
3f27282
·
verified ·
1 Parent(s): 519cae5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -144
app.py CHANGED
@@ -16,38 +16,39 @@ import base64
16
  # Set Gemini API Key
17
  client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  # --------- File Extractors ---------
20
  def extract_text_from_docx(docx_file):
21
- document = Document(docx_file)
22
- return "\n".join([para.text for para in document.paragraphs])
23
 
24
  def extract_text_from_csv(csv_file):
25
- df = pd.read_csv(csv_file)
26
- return df.to_string(index=False)
27
 
28
  def extract_text_from_xlsx(xlsx_file):
29
- df = pd.read_excel(xlsx_file)
30
- return df.to_string(index=False)
31
 
32
  def extract_text_from_pptx(pptx_file):
33
  prs = Presentation(pptx_file)
34
- text_runs = []
35
- for slide in prs.slides:
36
- for shape in slide.shapes:
37
- if hasattr(shape, "text"):
38
- text_runs.append(shape.text)
39
- return "\n".join(text_runs)
40
 
41
  def extract_text_from_pdf(pdf_file):
42
  doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
43
- text = ""
44
- for page in doc:
45
- text += page.get_text()
46
- return text
47
 
48
  def extract_text_from_html(html_file):
49
- soup = BeautifulSoup(html_file.read(), "html.parser")
50
- return soup.get_text()
51
 
52
  def extract_text_from_tex(tex_file):
53
  content = tex_file.read().decode("utf-8")
@@ -56,183 +57,131 @@ def extract_text_from_tex(tex_file):
56
  return content
57
 
58
  def process_image(image_file):
59
- image_bytes = image_file.read()
60
- encoded_image = base64.b64encode(image_bytes).decode("utf-8")
61
- return {
62
- "inline_data": {
63
- "mime_type": image_file.type,
64
- "data": encoded_image
65
- }
66
- }
67
 
68
  def process_video(video_file):
69
- video_bytes = video_file.read()
70
  filetype = video_file.name.split(".")[-1].lower()
71
  mime_map = {
72
- "avi": "video/x-msvideo",
73
- "mkv": "video/x-matroska",
74
- "flv": "video/x-flv",
75
- "wmv": "video/x-ms-wmv",
76
  "mpeg": "video/mpeg"
77
  }
78
  mime_type = mime_map.get(filetype, video_file.type)
79
- encoded_video = base64.b64encode(video_bytes).decode("utf-8")
80
- return {
81
- "inline_data": {
82
- "mime_type": mime_type,
83
- "data": encoded_video
84
- }
85
- }
86
 
87
  def export_conversation_to_pdf(conversation_history):
88
  pdf_path = "Conversation.pdf"
89
  doc = SimpleDocTemplate(pdf_path, pagesize=A4)
90
  styles = getSampleStyleSheet()
91
  elements = []
92
-
93
  for i, (user_q, gemini_a) in enumerate(conversation_history):
94
  elements.append(Paragraph(f"<b>Q{i+1}:</b> {user_q}", styles["Normal"]))
95
  elements.append(Spacer(1, 8))
96
  elements.append(Paragraph(f"<b>A{i+1}:</b> {gemini_a.replace(chr(10), '<br/>')}", styles["Normal"]))
97
  elements.append(Spacer(1, 16))
98
-
99
  doc.build(elements)
100
  return pdf_path
101
 
102
  # --------- Main App ---------
103
  def main():
104
- st.set_page_config(page_title="Gemini 2.0 Flash Chat Q&A", layout="wide")
105
- st.title("\U0001F4C4 Chat with Your Documents leveraging Internet Using Gemini 2.0 Flash (Team 18)")
106
-
107
- if "conversation" not in st.session_state:
108
- st.session_state.conversation = []
109
- if "documents_text" not in st.session_state:
110
- st.session_state.documents_text = []
111
- if "chat_active" not in st.session_state:
112
- st.session_state.chat_active = True
113
- if "chat_history" not in st.session_state:
114
- st.session_state.chat_history = []
115
 
116
  uploaded_files = st.file_uploader(
117
- "Upload files (.txt, .docx, .csv, .xlsx, .pptx, .pdf, .html, .htm, .tex, .jpg, .jpeg, .png, video formats):",
118
- type=[
119
- "txt", "docx", "csv", "xlsx", "pptx", "pdf", "html", "htm", "tex",
120
- "jpg", "jpeg", "png",
121
- "mp4", "webm", "mov", "avi", "mkv", "flv", "wmv", "mpeg"
122
- ],
123
  accept_multiple_files=True
124
  )
125
 
126
  if uploaded_files:
127
- all_text_content = ""
128
- for uploaded_file in uploaded_files:
129
- filetype = uploaded_file.name.split(".")[-1].lower()
130
  try:
131
- if filetype == "txt":
132
- all_text_content += uploaded_file.read().decode("utf-8") + "\n"
133
- elif filetype == "docx":
134
- all_text_content += extract_text_from_docx(uploaded_file) + "\n"
135
- elif filetype == "csv":
136
- all_text_content += extract_text_from_csv(uploaded_file) + "\n"
137
- elif filetype == "xlsx":
138
- all_text_content += extract_text_from_xlsx(uploaded_file) + "\n"
139
- elif filetype == "pptx":
140
- all_text_content += extract_text_from_pptx(uploaded_file) + "\n"
141
- elif filetype == "pdf":
142
- all_text_content += extract_text_from_pdf(uploaded_file) + "\n"
143
- elif filetype in ["html", "htm"]:
144
- all_text_content += extract_text_from_html(uploaded_file) + "\n"
145
- elif filetype == "tex":
146
- all_text_content += extract_text_from_tex(uploaded_file) + "\n"
147
- elif filetype in ["jpg", "jpeg", "png"]:
148
- st.session_state.image_data = process_image(uploaded_file)
149
- all_text_content += "Image uploaded and processed.\n"
150
- st.image(uploaded_file, caption=uploaded_file.name, use_container_width=True)
151
- elif filetype in ["mp4", "webm", "mov", "avi", "mkv", "flv", "wmv", "mpeg"]:
152
- st.session_state.video_data = process_video(uploaded_file)
153
- all_text_content += f"Video file '{uploaded_file.name}' uploaded and processed.\n"
154
- st.video(uploaded_file)
155
- else:
156
- st.error(f"Unsupported file format: {uploaded_file.name}")
157
  except Exception as e:
158
- st.error(f"Failed to extract/process {uploaded_file.name}: {e}")
159
-
160
- st.session_state.documents_text = all_text_content
161
 
162
  if st.session_state.documents_text:
163
- st.markdown("### \U0001F4AC Conversation")
164
- for user_q, gemini_a in st.session_state.conversation:
165
- st.markdown(f"**You:** {user_q}")
166
- st.markdown(f"**Gemini:**\n\n{gemini_a}")
167
 
168
  if st.session_state.chat_active:
169
- with st.form(key="chat_form", clear_on_submit=True):
170
- user_input = st.text_input("Ask a question about the documents (type 'exit' to stop):")
171
- submit = st.form_submit_button("Send")
172
-
173
- if submit and user_input:
174
  if user_input.strip().lower() == "exit":
175
  st.session_state.chat_active = False
176
- st.success("Chat ended. Reload to start again.")
177
  else:
178
  with st.spinner("Gemini is thinking..."):
179
- # -------- System context for Gemini --------
180
- system_context = {
181
- "role": "user",
182
- "text": (
183
- "You are part of an intelligent driver distraction detection system. "
184
- "Your role is to process images and videos to help identify and classify driver states, analyze documents, and answer the queries. "
185
- "including: drowsy, alert, yawning, microsleep, eyes/lips open or closed, and other distractions like safe driving, texting - right, talking on the phone - right,texting - left, talking on the phone - left, operating the radio, drinking, reaching behind,hair and makeup,talking to passenger."
186
- "The user may ask for timestamps of events in video, technical explanations from code/docs, "
187
- "or structured summaries. Prioritize your answers for this use case and be precise."
188
- "within this domain."
189
- )
190
- }
191
-
192
- content_blocks = [system_context]
193
 
194
  if st.session_state.conversation:
195
- history_text = "\n\n".join(
196
- f"Q: {entry[0]}\nA: {entry[1]}"
197
- for entry in st.session_state.conversation
198
- )
199
- content_blocks.append({"text": f"Previous conversation:\n{history_text}"})
200
 
201
- if st.session_state.documents_text.strip():
202
- content_blocks.append({"text": f"Context:\n{st.session_state.documents_text}"})
203
 
204
- if "image_data" in st.session_state:
205
- content_blocks.append(st.session_state.image_data)
206
 
207
- if "video_data" in st.session_state:
208
- content_blocks.append(st.session_state.video_data)
209
 
210
- content_blocks.append({"text": f"Question: {user_input}"})
211
 
212
- response = client.models.generate_content(
213
  model="gemini-2.0-flash",
214
- contents=content_blocks,
215
- config={"tools": [{"google_search": {}}]}
216
  )
217
 
218
  st.session_state.conversation.append((user_input, response.text))
219
- st.success("\U0001F4A1 Answer:")
220
  st.write(response.text)
221
 
222
- st.session_state.chat_history.append({
223
- "question": user_input,
224
- "answer": response.text
225
- })
226
-
227
- if st.session_state.conversation:
228
- pdf_path = export_conversation_to_pdf(st.session_state.conversation)
229
- with open(pdf_path, "rb") as f:
230
- st.download_button(
231
- label="\U0001F4E5 Export Conversation as PDF",
232
- data=f,
233
- file_name="Conversation.pdf",
234
- mime="application/pdf"
235
- )
236
 
237
  if __name__ == "__main__":
238
- main()
 
16
  # Set Gemini API Key
17
  client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
18
 
19
+ # System prompt
20
+ SYSTEM_PROMPT = (
21
+ "You are part of an intelligent driver distraction detection system. "
22
+ "Your role is to analyze documents, images, and videos to help identify and classify driver states, "
23
+ "including: drowsy, alert, yawning, microsleep, eyes/lips open or closed, and other distractions. "
24
+ "The user may ask for timestamps of events in video, technical explanations from code/docs, "
25
+ "or structured summaries. Prioritize your answers for this use case and act as a helpful assistant "
26
+ "within this domain. "
27
+ "Additionally, your classification may rely on the State Farm Distracted Driver Detection dataset, "
28
+ "which defines 10 distraction categories such as texting, phone use, reaching behind, adjusting the radio, "
29
+ "and safe driving. Use this labeling scheme when interpreting relevant images or video frames."
30
+ )
31
+
32
  # --------- File Extractors ---------
33
  def extract_text_from_docx(docx_file):
34
+ return "\n".join([para.text for para in Document(docx_file).paragraphs])
 
35
 
36
  def extract_text_from_csv(csv_file):
37
+ return pd.read_csv(csv_file).to_string(index=False)
 
38
 
39
  def extract_text_from_xlsx(xlsx_file):
40
+ return pd.read_excel(xlsx_file).to_string(index=False)
 
41
 
42
  def extract_text_from_pptx(pptx_file):
43
  prs = Presentation(pptx_file)
44
+ return "\n".join([shape.text for slide in prs.slides for shape in slide.shapes if hasattr(shape, "text")])
 
 
 
 
 
45
 
46
  def extract_text_from_pdf(pdf_file):
47
  doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
48
+ return "".join([page.get_text() for page in doc])
 
 
 
49
 
50
  def extract_text_from_html(html_file):
51
+ return BeautifulSoup(html_file.read(), "html.parser").get_text()
 
52
 
53
  def extract_text_from_tex(tex_file):
54
  content = tex_file.read().decode("utf-8")
 
57
  return content
58
 
59
  def process_image(image_file):
60
+ return types.Part.from_data(
61
+ data=image_file.read(),
62
+ mime_type=image_file.type
63
+ )
 
 
 
 
64
 
65
  def process_video(video_file):
 
66
  filetype = video_file.name.split(".")[-1].lower()
67
  mime_map = {
68
+ "avi": "video/x-msvideo", "mkv": "video/x-matroska",
69
+ "flv": "video/x-flv", "wmv": "video/x-ms-wmv",
 
 
70
  "mpeg": "video/mpeg"
71
  }
72
  mime_type = mime_map.get(filetype, video_file.type)
73
+ return types.Part.from_data(data=video_file.read(), mime_type=mime_type)
 
 
 
 
 
 
74
 
75
  def export_conversation_to_pdf(conversation_history):
76
  pdf_path = "Conversation.pdf"
77
  doc = SimpleDocTemplate(pdf_path, pagesize=A4)
78
  styles = getSampleStyleSheet()
79
  elements = []
 
80
  for i, (user_q, gemini_a) in enumerate(conversation_history):
81
  elements.append(Paragraph(f"<b>Q{i+1}:</b> {user_q}", styles["Normal"]))
82
  elements.append(Spacer(1, 8))
83
  elements.append(Paragraph(f"<b>A{i+1}:</b> {gemini_a.replace(chr(10), '<br/>')}", styles["Normal"]))
84
  elements.append(Spacer(1, 16))
 
85
  doc.build(elements)
86
  return pdf_path
87
 
88
  # --------- Main App ---------
89
  def main():
90
+ st.set_page_config(page_title="Driver State Chat with Gemini", layout="wide")
91
+ st.title("🚗 Chat with Driver Distraction Files using Gemini Flash (Team 18)")
92
+
93
+ for key in ["conversation", "documents_text", "chat_active", "chat_history", "image_data", "video_data"]:
94
+ if key not in st.session_state:
95
+ st.session_state[key] = [] if key == "conversation" else ""
 
 
 
 
 
96
 
97
  uploaded_files = st.file_uploader(
98
+ "Upload documents, images, or videos:",
99
+ type=["txt", "docx", "csv", "xlsx", "pptx", "pdf", "html", "htm", "tex",
100
+ "jpg", "jpeg", "png", "mp4", "webm", "mov", "avi", "mkv", "flv", "wmv", "mpeg"],
 
 
 
101
  accept_multiple_files=True
102
  )
103
 
104
  if uploaded_files:
105
+ all_text = ""
106
+ for f in uploaded_files:
107
+ ext = f.name.split(".")[-1].lower()
108
  try:
109
+ if ext == "txt":
110
+ all_text += f.read().decode("utf-8") + "\n"
111
+ elif ext == "docx":
112
+ all_text += extract_text_from_docx(f) + "\n"
113
+ elif ext == "csv":
114
+ all_text += extract_text_from_csv(f) + "\n"
115
+ elif ext == "xlsx":
116
+ all_text += extract_text_from_xlsx(f) + "\n"
117
+ elif ext == "pptx":
118
+ all_text += extract_text_from_pptx(f) + "\n"
119
+ elif ext == "pdf":
120
+ all_text += extract_text_from_pdf(f) + "\n"
121
+ elif ext in ["html", "htm"]:
122
+ all_text += extract_text_from_html(f) + "\n"
123
+ elif ext == "tex":
124
+ all_text += extract_text_from_tex(f) + "\n"
125
+ elif ext in ["jpg", "jpeg", "png"]:
126
+ st.session_state.image_data = process_image(f)
127
+ st.image(f, caption=f.name, use_container_width=True)
128
+ all_text += f"Image {f.name} uploaded.\n"
129
+ elif ext in ["mp4", "webm", "mov", "avi", "mkv", "flv", "wmv", "mpeg"]:
130
+ st.session_state.video_data = process_video(f)
131
+ st.video(f)
132
+ all_text += f"Video {f.name} uploaded.\n"
 
 
133
  except Exception as e:
134
+ st.error(f"Error processing {f.name}: {e}")
135
+ st.session_state.documents_text = all_text
 
136
 
137
  if st.session_state.documents_text:
138
+ st.markdown("### 💬 Chat")
139
+ for q, a in st.session_state.conversation:
140
+ st.markdown(f"**You:** {q}")
141
+ st.markdown(f"**Gemini:** {a}")
142
 
143
  if st.session_state.chat_active:
144
+ with st.form("chat_form", clear_on_submit=True):
145
+ user_input = st.text_input("Ask a question about the uploaded files:")
146
+ submitted = st.form_submit_button("Send")
147
+ if submitted and user_input:
 
148
  if user_input.strip().lower() == "exit":
149
  st.session_state.chat_active = False
150
+ st.success("Chat ended.")
151
  else:
152
  with st.spinner("Gemini is thinking..."):
153
+ messages = [
154
+ types.Content(role="user", parts=[types.Part(text=SYSTEM_PROMPT)])
155
+ ]
 
 
 
 
 
 
 
 
 
 
 
156
 
157
  if st.session_state.conversation:
158
+ conv = "\n".join([f"Q: {q}\nA: {a}" for q, a in st.session_state.conversation])
159
+ messages.append(types.Content(role="user", parts=[types.Part(text=conv)]))
 
 
 
160
 
161
+ if st.session_state.documents_text:
162
+ messages.append(types.Content(role="user", parts=[types.Part(text=st.session_state.documents_text)]))
163
 
164
+ if st.session_state.image_data:
165
+ messages.append(types.Content(role="user", parts=[st.session_state.image_data]))
166
 
167
+ if st.session_state.video_data:
168
+ messages.append(types.Content(role="user", parts=[st.session_state.video_data]))
169
 
170
+ messages.append(types.Content(role="user", parts=[types.Part(text=user_input)]))
171
 
172
+ response = client.generate_content(
173
  model="gemini-2.0-flash",
174
+ contents=messages
 
175
  )
176
 
177
  st.session_state.conversation.append((user_input, response.text))
178
+ st.success("💡 Answer:")
179
  st.write(response.text)
180
 
181
+ if st.session_state.conversation:
182
+ pdf_path = export_conversation_to_pdf(st.session_state.conversation)
183
+ with open(pdf_path, "rb") as f:
184
+ st.download_button("⬇️ Export Conversation as PDF", f, "Conversation.pdf", "application/pdf")
 
 
 
 
 
 
 
 
 
 
185
 
186
  if __name__ == "__main__":
187
+ main()