Shakir60 commited on
Commit
a18da93
·
verified ·
1 Parent(s): a5d5682

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -29
app.py CHANGED
@@ -1,14 +1,11 @@
1
- import time
2
  from streamlit_extras.colored_header import colored_header
3
  from streamlit_extras.add_vertical_space import add_vertical_space
4
- from streamlit_card import card
5
- import plotly.graph_objects as go
6
- import streamlit as st
7
- import torch
8
  from PIL import Image
9
  import numpy as np
10
  from transformers import ViTFeatureExtractor, ViTForImageClassification
11
  from sentence_transformers import SentenceTransformer
 
 
12
  import matplotlib.pyplot as plt
13
  import logging
14
  import faiss
@@ -17,6 +14,9 @@ from datetime import datetime
17
  from groq import Groq
18
  import os
19
  from functools import lru_cache
 
 
 
20
 
21
  # Setup logging
22
  logging.basicConfig(level=logging.INFO)
@@ -343,8 +343,23 @@ def get_groq_response(query: str, context: str) -> str:
343
  return f"Error: Unable to get response from AI model. Exception: {str(e)}"
344
 
345
 
346
- def create_plotly_confidence_chart(results):
347
- """Create an interactive confidence chart using Plotly"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348
  fig = go.Figure(data=[
349
  go.Bar(
350
  x=list(results.values()),
@@ -360,28 +375,39 @@ def create_plotly_confidence_chart(results):
360
  title='Defect Detection Confidence Levels',
361
  xaxis_title='Confidence',
362
  yaxis_title='Defect Type',
363
- template='plotly_white',
364
  height=400,
365
  margin=dict(l=20, r=20, t=40, b=20),
366
- xaxis=dict(range=[0, 1])
 
 
 
367
  )
 
368
  return fig
369
 
370
  def create_defect_card(title, description, severity, repair_method):
371
- """Create a styled card for defect information"""
372
  severity_colors = {
373
- "Critical": "red",
374
- "High": "orange",
375
- "Medium": "yellow",
376
- "Low": "green"
377
  }
378
 
 
 
 
 
 
 
 
379
  return f"""
380
- <div style="border: 1px solid #ddd; border-radius: 10px; padding: 15px; margin: 10px 0;">
381
- <h3 style="color: #1f77b4; margin: 0 0 10px 0;">{title}</h3>
382
  <p><strong>Description:</strong> {description}</p>
383
  <p><strong>Severity:</strong>
384
- <span style="color: {severity_colors.get(severity, 'gray')}">
385
  {severity}
386
  </span>
387
  </p>
@@ -389,6 +415,47 @@ def create_defect_card(title, description, severity, repair_method):
389
  </div>
390
  """
391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
  def main():
393
  st.set_page_config(
394
  page_title="Smart Construction Defect Analyzer",
@@ -397,12 +464,12 @@ def main():
397
  initial_sidebar_state="expanded"
398
  )
399
 
400
- # Custom CSS
 
 
 
401
  st.markdown("""
402
  <style>
403
- .stApp {
404
- background-color: #f8f9fa;
405
- }
406
  .css-1d391kg {
407
  padding: 2rem 1rem;
408
  }
@@ -412,12 +479,9 @@ def main():
412
  .upload-text {
413
  text-align: center;
414
  padding: 2rem;
415
- border: 2px dashed #ccc;
416
  border-radius: 10px;
417
- background-color: #ffffff;
418
  }
419
  .info-box {
420
- background-color: #e9ecef;
421
  padding: 1rem;
422
  border-radius: 10px;
423
  margin: 1rem 0;
@@ -441,6 +505,13 @@ def main():
441
  color_name="blue-70"
442
  )
443
 
 
 
 
 
 
 
 
444
  if os.getenv("GROQ_API_KEY"):
445
  st.success("🟢 AI System: Connected")
446
  else:
@@ -516,9 +587,9 @@ def main():
516
  if uploaded_file and results:
517
  st.markdown("### Analysis Results")
518
 
519
- # Interactive confidence chart
520
- fig = create_plotly_confidence_chart(results)
521
- st.plotly_chart(fig, use_container_width=True)
522
 
523
  # Most critical defect
524
  most_likely_defect = max(results.items(), key=lambda x: x[1])[0]
@@ -564,10 +635,29 @@ def main():
564
  with col1:
565
  st.image(analysis['image'], caption='Analyzed Image', use_column_width=True)
566
  with col2:
567
- fig = create_plotly_confidence_chart(analysis['results'])
568
- st.plotly_chart(fig, use_container_width=True)
 
569
  else:
570
  st.info("No analysis history available")
571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
572
  if __name__ == "__main__":
573
  main()
 
 
1
  from streamlit_extras.colored_header import colored_header
2
  from streamlit_extras.add_vertical_space import add_vertical_space
 
 
 
 
3
  from PIL import Image
4
  import numpy as np
5
  from transformers import ViTFeatureExtractor, ViTForImageClassification
6
  from sentence_transformers import SentenceTransformer
7
+ import streamlit as st
8
+ import torch
9
  import matplotlib.pyplot as plt
10
  import logging
11
  import faiss
 
14
  from groq import Groq
15
  import os
16
  from functools import lru_cache
17
+ import time
18
+ from streamlit_card import card
19
+ import plotly.graph_objects as go
20
 
21
  # Setup logging
22
  logging.basicConfig(level=logging.INFO)
 
343
  return f"Error: Unable to get response from AI model. Exception: {str(e)}"
344
 
345
 
346
+ def create_plotly_confidence_chart(results, chart_id):
347
+ """Create an interactive confidence chart using Plotly with unique ID"""
348
+ colors = {
349
+ 'light': {
350
+ 'bg': 'white',
351
+ 'text': 'black',
352
+ 'grid': '#eee'
353
+ },
354
+ 'dark': {
355
+ 'bg': '#262730',
356
+ 'text': 'white',
357
+ 'grid': '#333'
358
+ }
359
+ }
360
+
361
+ theme = 'dark' if st.get_option('theme.base') == 'dark' else 'light'
362
+
363
  fig = go.Figure(data=[
364
  go.Bar(
365
  x=list(results.values()),
 
375
  title='Defect Detection Confidence Levels',
376
  xaxis_title='Confidence',
377
  yaxis_title='Defect Type',
378
+ template='plotly_dark' if theme == 'dark' else 'plotly_white',
379
  height=400,
380
  margin=dict(l=20, r=20, t=40, b=20),
381
+ xaxis=dict(range=[0, 1]),
382
+ plot_bgcolor=colors[theme]['bg'],
383
+ paper_bgcolor=colors[theme]['bg'],
384
+ font=dict(color=colors[theme]['text'])
385
  )
386
+
387
  return fig
388
 
389
  def create_defect_card(title, description, severity, repair_method):
390
+ """Create a styled card for defect information with theme support"""
391
  severity_colors = {
392
+ "Critical": "#ff4444",
393
+ "High": "#ffa000",
394
+ "Medium": "#ffeb3b",
395
+ "Low": "#4caf50"
396
  }
397
 
398
+ # Get current theme
399
+ is_dark = st.get_option('theme.base') == 'dark'
400
+
401
+ bg_color = '#1e1e1e' if is_dark else '#ffffff'
402
+ text_color = '#ffffff' if is_dark else '#000000'
403
+ border_color = '#333333' if is_dark else '#dddddd'
404
+
405
  return f"""
406
+ <div style="border: 1px solid {border_color}; border-radius: 10px; padding: 15px; margin: 10px 0; background-color: {bg_color}; color: {text_color};">
407
+ <h3 style="color: {'#00a0dc' if is_dark else '#1f77b4'}; margin: 0 0 10px 0;">{title}</h3>
408
  <p><strong>Description:</strong> {description}</p>
409
  <p><strong>Severity:</strong>
410
+ <span style="color: {severity_colors.get(severity, '#808080')}">
411
  {severity}
412
  </span>
413
  </p>
 
415
  </div>
416
  """
417
 
418
+ def get_theme_specific_styles():
419
+ """Get theme-specific CSS styles"""
420
+ is_dark = st.get_option('theme.base') == 'dark'
421
+
422
+ if is_dark:
423
+ return """
424
+ <style>
425
+ .stApp {
426
+ background-color: #0e1117;
427
+ }
428
+ .upload-text {
429
+ border: 2px dashed #444;
430
+ background-color: #1e1e1e;
431
+ }
432
+ .info-box {
433
+ background-color: #262730;
434
+ border: 1px solid #333;
435
+ }
436
+ .stAlert {
437
+ background-color: #262730;
438
+ border: 1px solid #333;
439
+ }
440
+ </style>
441
+ """
442
+ else:
443
+ return """
444
+ <style>
445
+ .stApp {
446
+ background-color: #f8f9fa;
447
+ }
448
+ .upload-text {
449
+ border: 2px dashed #ccc;
450
+ background-color: #ffffff;
451
+ }
452
+ .info-box {
453
+ background-color: #e9ecef;
454
+ border: 1px solid #dee2e6;
455
+ }
456
+ </style>
457
+ """
458
+
459
  def main():
460
  st.set_page_config(
461
  page_title="Smart Construction Defect Analyzer",
 
464
  initial_sidebar_state="expanded"
465
  )
466
 
467
+ # Apply theme-specific styles
468
+ st.markdown(get_theme_specific_styles(), unsafe_allow_html=True)
469
+
470
+ # Base CSS that works for both themes
471
  st.markdown("""
472
  <style>
 
 
 
473
  .css-1d391kg {
474
  padding: 2rem 1rem;
475
  }
 
479
  .upload-text {
480
  text-align: center;
481
  padding: 2rem;
 
482
  border-radius: 10px;
 
483
  }
484
  .info-box {
 
485
  padding: 1rem;
486
  border-radius: 10px;
487
  margin: 1rem 0;
 
505
  color_name="blue-70"
506
  )
507
 
508
+ # Theme selector
509
+ theme = st.selectbox(
510
+ "Choose Theme",
511
+ options=["Light", "Dark"],
512
+ index=1 if st.get_option('theme.base') == 'dark' else 0
513
+ )
514
+
515
  if os.getenv("GROQ_API_KEY"):
516
  st.success("🟢 AI System: Connected")
517
  else:
 
587
  if uploaded_file and results:
588
  st.markdown("### Analysis Results")
589
 
590
+ # Interactive confidence chart with unique ID
591
+ fig = create_plotly_confidence_chart(results, "main_analysis")
592
+ st.plotly_chart(fig, use_container_width=True, key="main_chart")
593
 
594
  # Most critical defect
595
  most_likely_defect = max(results.items(), key=lambda x: x[1])[0]
 
635
  with col1:
636
  st.image(analysis['image'], caption='Analyzed Image', use_column_width=True)
637
  with col2:
638
+ # Create chart with unique ID for history items
639
+ fig = create_plotly_confidence_chart(analysis['results'], f"history_{i}")
640
+ st.plotly_chart(fig, use_container_width=True, key=f"history_chart_{i}")
641
  else:
642
  st.info("No analysis history available")
643
 
644
+ # Handle theme change
645
+ if theme == "Dark" and st.get_option('theme.base') != 'dark':
646
+ st.markdown("""
647
+ <script>
648
+ var elements = window.parent.document.getElementsByTagName('iframe');
649
+ for (var i = 0; i < elements.length; i++) {
650
+ if (elements[i].height === '0') {
651
+ elements[i].remove();
652
+ }
653
+ }
654
+ </script>
655
+ """, unsafe_allow_html=True)
656
+ st.experimental_set_query_params(theme='dark')
657
+ st.experimental_rerun()
658
+ elif theme == "Light" and st.get_option('theme.base') != 'light':
659
+ st.experimental_set_query_params(theme='light')
660
+ st.experimental_rerun()
661
+
662
  if __name__ == "__main__":
663
  main()