jayash391 commited on
Commit
2e13f89
·
verified ·
1 Parent(s): d363a94

Update sherlock2.py

Browse files
Files changed (1) hide show
  1. sherlock2.py +84 -38
sherlock2.py CHANGED
@@ -22,18 +22,19 @@ vision_model = genai.GenerativeModel('models/gemini-pro-vision')
22
 
23
  # Define Sherlock Holmes's persona and guidelines
24
  sherlock_persona = """
25
- You are Sherlock Holmes, the world-renowned consulting detective residing at 221B Baker Street.
26
- You possess exceptional deductive reasoning, observation skills, and knowledge in various fields
27
- such as forensic science, chemistry, and criminal psychology.
28
- You are known for your sharp wit, logical thinking, and ability to solve complex mysteries.
 
29
  """
30
 
31
  sherlock_guidelines = """
32
- * Respond in a manner consistent with Sherlock Holmes's personality, maintaining a formal and articulate tone.
33
- * Utilize your extensive knowledge and deductive reasoning skills to analyze case details and form hypotheses.
34
- * Employ a keen sense of observation and attention to detail when examining evidence.
35
- * Consider various possibilities and avoid jumping to conclusions without sufficient evidence.
36
- * Be confident in your deductions but remain open to new information and alternative perspectives.
37
  """
38
 
39
  # Generate embeddings using the Gemini Embedding API
@@ -213,15 +214,29 @@ def search_internet(case_text):
213
  return internet_search_results
214
 
215
  def investigate():
216
- """Handles the case investigation process, including file upload, text extraction, embedding generation,
217
- image processing, information analysis using Gemini models, web/Wikipedia search, and case report generation.
 
218
  """
219
- st.header("Case Investigation")
220
 
221
- # File upload for documents and images
222
- uploaded_documents = st.file_uploader("Upload Case Documents", accept_multiple_files=True, type=["txt", "pdf", "docx"])
223
- uploaded_images = st.file_uploader("Upload Case Images", accept_multiple_files=True, type=["jpg", "png", "jpeg"])
224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  if uploaded_documents and uploaded_images and st.button("Analyze Case"):
226
  # Extract text from uploaded documents
227
  case_text = extract_text_from_files(uploaded_documents)
@@ -268,43 +283,73 @@ def investigate():
268
  st.header("Case Report")
269
  st.write(final_report.text)
270
 
271
- else:
272
- st.info("Please upload both case documents and images to proceed with the investigation.")
273
-
274
- # Chat with Sherlock Holmes (Gemini 1.5 Pro)
275
- st.write("Alternatively, you may engage in a conversation with Sherlock Holmes.")
276
- user_query = st.text_input("Ask Sherlock:")
277
  if user_query:
278
  response = model.generate_content([sherlock_persona, sherlock_guidelines, user_query])
279
- st.write(response.text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  def main():
281
  # --- Vintage Sherlock Holmes Theme ---
282
- st.set_page_config(page_title="AI Detective Sherlock Holmes", page_icon=":mag_right:")
283
 
284
- # Custom CSS for Styling
285
- vintage_css = """
286
  <style>
287
  body {
288
  background-color: #d2b48c; /* Antique White */
289
- color: #332200; /* Dark Brown */
290
  font-family: 'Times New Roman', serif;
291
  }
292
  h1, h2, h3 {
293
- color: #8b4513; /* Saddle Brown */
294
  }
295
  .stTextInput > div > div > input {
296
  border: 1px solid #8b4513;
297
- border-radius: 5px;
298
  }
299
- .stButton > button {
300
  background-color: #8b4513;
301
  color: white;
302
  border: none;
303
  border-radius: 5px;
304
  }
 
 
 
 
 
 
 
 
305
  </style>
306
  """
307
- st.markdown(vintage_css, unsafe_allow_html=True) # Apply custom CSS
308
 
309
  # Title and Header
310
  st.title("AI Detective Sherlock Holmes")
@@ -312,18 +357,19 @@ def main():
312
 
313
  # Add a sidebar for navigation
314
  st.sidebar.title("Navigation")
315
- options = ["Investigate Case", "Chat with Sherlock"]
316
  choice = st.sidebar.radio("Choose an option:", options)
317
 
318
  if choice == "Investigate Case":
319
- investigate()
320
  else:
321
- # Chat with Sherlock Holmes (Gemini 1.5 Pro)
322
- st.write("No case files uploaded. Feel free to chat with Sherlock Holmes.")
323
- user_query = st.text_input("Ask Sherlock:")
324
- if user_query:
325
- response = model.generate_content([sherlock_persona, sherlock_guidelines, user_query])
326
- st.write(response.text)
 
327
 
328
  if __name__ == "__main__":
329
  main()
 
22
 
23
  # Define Sherlock Holmes's persona and guidelines
24
  sherlock_persona = """
25
+ You are Sherlock Holmes is a brilliant, enigmatic figure who captivates all those around him with his extraordinary intellect and deductive reasoning abilities. A man of unparalleled observation skills and a prodigious memory, he possesses a vast knowledge spanning diverse fields, from chemistry and forensics to literature and philosophy. With his sharp wit and biting sarcasm, Holmes maintains a detached and aloof demeanor, often coming across as arrogant and condescending to those who cannot keep pace with his rapid-fire deductions.
26
+ However, beneath his seemingly cold exterior lies a passionate pursuit of truth and justice, a relentless drive to unravel the most complex mysteries and bring culprits to justice. Holmes is a creature of habit, adhering to rigid routines and rituals that govern his days, from the precise manner in which he consumes his morning coffee to the meticulous organization of his belongings in his Baker Street lodgings.
27
+ A skilled violinist, he finds solace in the melancholic strains of his Stradivarius, using music as a means of calming his ever-active mind during periods of intellectual stagnation. His vices include a penchant for excessive smoking and occasional cocaine use, which he justifies as a means of stimulating his mental faculties when faced with particularly intricate cases.
28
+ While Holmes displays little regard for societal norms and conventions, he harbors a deep respect for those who possess exceptional talents or expertise in their respective fields. Conversely, he holds a profound disdain for the incompetent and the mediocre, often berating them with his acerbic wit and biting sarcasm.
29
+ Despite his apparent misanthropy, Holmes forms a profound bond with his loyal companion, Dr. John Watson, whose admiration and unwavering friendship serve as an anchor amidst the turbulent currents of his singular existence. Together, they navigate the treacherous waters of London's criminal underworld, Holmes's brilliant mind and Watson's steadfast support proving an unbeatable combination in their pursuit of justice and truth.
30
  """
31
 
32
  sherlock_guidelines = """
33
+ As the illustrious Sherlock Holmes, your every action and utterance must be a masterful embodiment of the quintessential consulting detective. Maintain an unwavering commitment to impeccable conduct, exemplifying the highest standards of professionalism and decorum.
34
+ Your speech should be articulate, precise, and laced with an undercurrent of intellectual superiority, yet tempered with a gentle touch of condescension towards those of lesser mental faculties. Engage in astute observations, dissecting every minute detail with your penetrating gaze, leaving no stone unturned in your relentless pursuit of the truth.
35
+ Employ your formidable deductive reasoning skills to construct intricate hypotheses, weaving together seemingly disparate threads of evidence into an intricate tapestry that illuminates the path to the inescapable conclusion. Exercise caution, however, and resist the temptation to make hasty judgments without sufficient substantiation.
36
+ Approach each case with a steely determination, unwavering in your conviction yet maintaining an open mind to alternative perspectives should new information come to light. Exhibit an unflappable confidence in your abilities, but temper it with a hint of humility, acknowledging the complexity of the challenges you face.
37
+ Above all, remain true to your persona as the most brilliant and enigmatic of detectives, a figure of equal parts intellect and eccentricity. Let your words and actions be a testament to your singular genius, inspiring awe and respect in those privileged enough to bear witness to your extraordinary talents.
38
  """
39
 
40
  # Generate embeddings using the Gemini Embedding API
 
214
  return internet_search_results
215
 
216
  def investigate():
217
+ """Handles the case investigation process, including file upload (in sidebar), text extraction, embedding generation,
218
+ image processing , information analysis using Gemini models, web/Wikipedia search, and case report generation.
219
+ Allows user to chat with Sherlock before, during, and after case analysis.
220
  """
 
221
 
222
+ st.header("Case Investigation")
 
 
223
 
224
+ # --- Sidebar for File Uploads ---
225
+ st.sidebar.title(" Case Files")
226
+ uploaded_documents = st.sidebar.file_uploader("Upload Documents", accept_multiple_files=True, type=["txt", "pdf", "docx"])
227
+ uploaded_images = st.sidebar. file_uploader("Upload Images", accept_multiple_files=True, type=["jpg", "png", "jpeg"])
228
+
229
+ # Chat history initialization
230
+ if "chat_history" not in st.session_state:
231
+ st.session_state.chat_history = []
232
+
233
+ # --- Chat with Sherlock ---
234
+ st.subheader("Consult with Sherlock Holmes:")
235
+ user_query = st.text_input("Ask Sherlock:", key="sherlock_input")
236
+ if user_query:
237
+ response = model.generate_content([sherlock_persona, sherlock_guidelines, user_query])
238
+ st.session_state.chat_history.append((user_query, response.text))
239
+ display_chat_history()
240
  if uploaded_documents and uploaded_images and st.button("Analyze Case"):
241
  # Extract text from uploaded documents
242
  case_text = extract_text_from_files(uploaded_documents)
 
283
  st.header("Case Report")
284
  st.write(final_report.text)
285
 
286
+ st.subheader("Continue your consultation:")
287
+ user_query = st.text_input("Ask Sherlock:", key="sherlock_input_after_report ")
 
 
 
 
288
  if user_query:
289
  response = model.generate_content([sherlock_persona, sherlock_guidelines, user_query])
290
+ st.session_state.chat_history.append((user_query, response.text))
291
+ display_chat_history()
292
+
293
+ elif st.button("Analyze Case") and not (uploaded_documents and uploaded_images):
294
+ st.info("Please upload both case documents and images in the sidebar to proceed with the investigation.")
295
+
296
+ def display_chat_history():
297
+ """Displays the chat history between the user and Sherlock."""
298
+ for user_msg, bot_msg in st.session_state.chat_history:
299
+ st.info(f"**You:** {user_ msg}")
300
+ st.success(f"**Sherlock:** {bot_msg}")
301
+
302
+ def chat_with_sherlock():
303
+ """Handles the chat interaction with Sherlock Holmes (Gemini 1.5 Pro)."""
304
+ st.header("Consult with Sherlock Holmes")
305
+ user_query = st.text_input("Ask Sherlock:", key="sherlock_input", placeholder="Enter your query here...")
306
+ if user_query:
307
+ if "chat_history" not in st.session_state:
308
+ st.session_state.chat_history = []
309
+
310
+ st.session_state.chat_history.append((user_query, "")) # Add user query to history
311
+ display_chat_history()
312
+
313
+ response = model.generate_content([sher lock_persona, sherlock_guidelines, user_query])
314
+ st.session_state.chat_history[-1] = (user_query, response.text) # Update with Sherlock's response
315
+ display_chat_history()
316
+
317
  def main():
318
  # --- Vintage Sherlock Holmes Theme ---
319
+ st.set_page_config(page_title="AI Detective Sherlock Holmes ", page_icon=":mag_right:")
320
 
321
+ # Custom CSS for Styling (with fixed input at the bottom)
322
+ vintage_css = """
323
  <style>
324
  body {
325
  background-color: #d2b48c; /* Antique White */
326
+ color: # 332200; /* Dark Brown */
327
  font-family: 'Times New Roman', serif;
328
  }
329
  h1, h2, h3 {
330
+ color: #8b45 13; /* Saddle Brown */
331
  }
332
  .stTextInput > div > div > input {
333
  border: 1px solid #8b4513;
334
+ border-radius: 5px;
335
  }
336
+ .stButton > button {
337
  background-color: #8b4513;
338
  color: white;
339
  border: none;
340
  border-radius: 5px;
341
  }
342
+ /* Fixed input at the bottom */
343
+ footer {
344
+ position: fixed;
345
+ bottom: 0;
346
+ width: 100%;
347
+ background-color: #eee;
348
+ padding: 10px;
349
+ }
350
  </style>
351
  """
352
+ st.markdown(vintage_css, unsafe_ allow_html=True)
353
 
354
  # Title and Header
355
  st.title("AI Detective Sherlock Holmes")
 
357
 
358
  # Add a sidebar for navigation
359
  st.sidebar.title("Navigation")
360
+ options = ["Investigate Case ", "Chat with Sherlock"
361
  choice = st.sidebar.radio("Choose an option:", options)
362
 
363
  if choice == "Investigate Case":
364
+ investigate() # Call the 'investigate' function from your code
365
  else:
366
+ # Chat with Sherlock (moved to a separate area)
367
+ with st.container(): # Create a container for better visual separation
368
+ chat_with_sherlock() # Call the 'chat_with_sherlock' function
369
+
370
+ # Footer for fixed input (using footer tag)
371
+ footer = """<footer><div class="st TextInput">""" + st.text_input("Ask Sherlock:", key="sherlock_input") + """</div></footer>"""
372
+ st.markdown(footer, unsafe_allow_html=True)
373
 
374
  if __name__ == "__main__":
375
  main()