redxican commited on
Commit
89f3f56
·
verified ·
1 Parent(s): 8e2efe0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -125
app.py CHANGED
@@ -1,7 +1,7 @@
1
  #!/usr/bin/env python3
2
  """
3
  Turbo Air Viewer - Equipment Specification Database Viewer
4
- Deployment-ready version with automatic database download
5
  """
6
 
7
  import streamlit as st
@@ -16,6 +16,7 @@ import base64
16
  import io
17
  import os
18
  import requests
 
19
 
20
  # Streamlit page config MUST be first
21
  st.set_page_config(
@@ -492,165 +493,88 @@ def export_bookmarked_models():
492
  return df.to_csv(index=False)
493
 
494
  def display_pdf_preview(file_path, model_name):
495
- """Optimized PDF display for Hugging Face Spaces with multiple fallbacks"""
496
- import os
497
- import requests
498
- from urllib.parse import quote
499
 
500
  # Extract filename from path
501
- normalized_path = file_path.replace('\\', '/')
502
- pdf_filename = normalized_path.split('/')[-1]
503
 
504
- # Create the Hugging Face URL
505
- base_url = "https://huggingface.co/spaces/TurboAir/TurboAirViewer/resolve/main/pdfs/"
506
- pdf_url = base_url + quote(pdf_filename)
507
-
508
- # Check if running locally or on Hugging Face
509
- is_local = not os.environ.get('SPACE_ID')
510
 
511
  # Control buttons row
512
  col1, col2, col3 = st.columns([2, 1, 1])
513
 
514
  with col1:
515
- # Try to get file size for better UX
516
  try:
517
- if is_local and os.path.exists(os.path.join('pdfs', pdf_filename)):
518
- file_size = os.path.getsize(os.path.join('pdfs', pdf_filename)) / (1024 * 1024)
519
- button_text = f"📥 Download PDF ({file_size:.1f} MB)"
 
 
 
 
 
 
 
520
  else:
521
- # Quick HEAD request to get file size from URL
522
- response = requests.head(pdf_url, timeout=5)
523
- if 'content-length' in response.headers:
524
- file_size = int(response.headers['content-length']) / (1024 * 1024)
525
- button_text = f"📥 Download PDF ({file_size:.1f} MB)"
526
- else:
527
- button_text = "📥 Download PDF"
528
  except:
529
- button_text = "📥 Download PDF"
530
-
531
- # Styled download button
532
- st.markdown(f'''
533
- <a href="{pdf_url}" download="{pdf_filename}" style="text-decoration: none;">
534
- <div style="
535
- background-color: #FF4B4B;
536
- color: white;
537
- padding: 0.5rem 1rem;
538
- border-radius: 0.25rem;
539
- text-align: center;
540
- cursor: pointer;
541
- font-weight: 500;
542
- transition: background-color 0.2s;
543
- display: block;
544
- " onmouseover="this.style.backgroundColor='#E04040'"
545
- onmouseout="this.style.backgroundColor='#FF4B4B'">
546
- {button_text}
547
- </div>
548
- </a>
549
- ''', unsafe_allow_html=True)
550
 
551
  with col2:
552
- st.markdown('''
553
- <div style="
554
- background-color: #0E1117;
555
- border: 1px solid #0F9D58;
556
- color: #0F9D58;
557
- padding: 0.5rem;
558
- border-radius: 0.25rem;
559
- text-align: center;
560
- font-size: 0.9rem;
561
- ">
562
- ✅ PDF ready
563
- </div>
564
- ''', unsafe_allow_html=True)
565
 
566
  with col3:
567
- if st.button("❌ Close Preview", use_container_width=True, type="secondary"):
568
  st.session_state[f'show_pdf_{model_name}'] = False
569
  st.rerun()
570
 
571
  st.markdown("---")
572
 
573
- # Method 1: Direct iframe (fastest, works if CORS allows)
574
- pdf_display_html = f'''
575
- <div style="width: 100%; height: 900px; position: relative;">
576
- <iframe
577
- id="pdf-frame"
578
- src="{pdf_url}"
579
  width="100%"
580
- height="100%"
581
- style="border: 1px solid #333; border-radius: 4px;"
582
- loading="lazy">
583
- </iframe>
584
  </div>
 
585
 
586
- <script>
587
- // Fallback to PDF.js if direct viewing fails
588
- setTimeout(function() {{
589
- var iframe = document.getElementById('pdf-frame');
590
- if (!iframe.contentWindow || !iframe.contentDocument) {{
591
- iframe.src = 'https://mozilla.github.io/pdf.js/web/viewer.html?file=' + encodeURIComponent('{pdf_url}');
592
- }}
593
- }}, 3000);
594
- </script>
595
- '''
596
-
597
- # Try direct display first
598
- st.markdown(pdf_display_html, unsafe_allow_html=True)
599
-
600
- # Provide alternative viewing options
601
  st.markdown("---")
 
602
 
603
  col1, col2, col3 = st.columns(3)
604
 
605
  with col1:
606
- st.markdown(f"📄 [Open in new tab ↗]({pdf_url})")
607
 
608
  with col2:
609
  # PDF.js viewer as backup
610
  pdf_js_url = f"https://mozilla.github.io/pdf.js/web/viewer.html?file={quote(pdf_url, safe='')}"
611
- st.markdown(f"🔍 [Open with PDF.js viewer ↗]({pdf_js_url})")
612
-
613
- with col3:
614
- # Google Docs viewer as another backup
615
- google_viewer_url = f"https://docs.google.com/viewer?url={quote(pdf_url, safe='')}&embedded=true"
616
- st.markdown(f"📑 [Open with Google viewer ↗]({google_viewer_url})")
617
-
618
- # Source info (matching your UI)
619
- if file_path:
620
- st.caption(f"Source: {file_path}")
621
-
622
-
623
- # Alternative lightweight version if the above has issues
624
- def display_pdf_preview_simple(file_path, model_name):
625
- """Simplified version with guaranteed compatibility"""
626
- import urllib.parse
627
-
628
- # Extract filename
629
- pdf_filename = os.path.basename(file_path.replace('\\', '/'))
630
-
631
- # Create URLs
632
- pdf_url = f"https://huggingface.co/spaces/TurboAir/TurboAirViewer/resolve/main/pdfs/{urllib.parse.quote(pdf_filename)}"
633
- viewer_url = f"https://mozilla.github.io/pdf.js/web/viewer.html?file={urllib.parse.quote(pdf_url, safe='')}"
634
-
635
- # Controls
636
- col1, col2, col3 = st.columns([2, 1, 1])
637
-
638
- with col1:
639
- st.markdown(f'<a href="{pdf_url}" target="_blank"><button style="width:100%;background:#FF4B4B;color:white;border:none;padding:8px;border-radius:4px;cursor:pointer">📥 Download PDF</button></a>', unsafe_allow_html=True)
640
-
641
- with col2:
642
- st.success("✅ PDF ready")
643
 
644
  with col3:
645
- if st.button("❌ Close Preview", use_container_width=True):
646
- st.session_state[f'show_pdf_{model_name}'] = False
647
- st.rerun()
648
 
649
- # Display
650
- st.markdown(f'<iframe src="{viewer_url}" width="100%" height="900" style="border:1px solid #333;border-radius:4px;"></iframe>', unsafe_allow_html=True)
651
-
652
- # Fallback
653
- st.caption(f"Can't see the PDF? [Click here to open]({pdf_url})")
 
 
 
 
 
 
654
 
655
  def get_high_accuracy_models(limit=8):
656
  """Get models with highest extraction quality"""
 
1
  #!/usr/bin/env python3
2
  """
3
  Turbo Air Viewer - Equipment Specification Database Viewer
4
+ Deployment-ready version with automatic database download and inline PDF display
5
  """
6
 
7
  import streamlit as st
 
16
  import io
17
  import os
18
  import requests
19
+ from urllib.parse import quote
20
 
21
  # Streamlit page config MUST be first
22
  st.set_page_config(
 
493
  return df.to_csv(index=False)
494
 
495
  def display_pdf_preview(file_path, model_name):
496
+ """Display PDF inline in Streamlit app - optimized for HuggingFace Spaces"""
 
 
 
497
 
498
  # Extract filename from path
499
+ pdf_filename = file_path.replace('\\', '/').split('/')[-1]
 
500
 
501
+ # Create the HuggingFace Space URL for the PDF
502
+ pdf_url = f"https://huggingface.co/spaces/TurboAir/TurboAirViewer/resolve/main/pdfs/{pdf_filename}"
 
 
 
 
503
 
504
  # Control buttons row
505
  col1, col2, col3 = st.columns([2, 1, 1])
506
 
507
  with col1:
508
+ # Download button with actual file download
509
  try:
510
+ response = requests.get(pdf_url, timeout=10)
511
+ if response.status_code == 200:
512
+ st.download_button(
513
+ label="📥 Download PDF",
514
+ data=response.content,
515
+ file_name=pdf_filename,
516
+ mime="application/pdf",
517
+ use_container_width=True,
518
+ type="primary"
519
+ )
520
  else:
521
+ # Fallback to link if download fails
522
+ st.markdown(f"[📥 Download PDF]({pdf_url})")
 
 
 
 
 
523
  except:
524
+ # Fallback to simple link
525
+ st.markdown(f"[📥 Download PDF]({pdf_url})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526
 
527
  with col2:
528
+ st.success("✅ PDF ready")
 
 
 
 
 
 
 
 
 
 
 
 
529
 
530
  with col3:
531
+ if st.button("❌ Close Preview", use_container_width=True):
532
  st.session_state[f'show_pdf_{model_name}'] = False
533
  st.rerun()
534
 
535
  st.markdown("---")
536
 
537
+ # Display PDF inline using embed tag (most reliable for HuggingFace Spaces)
538
+ st.markdown(f'''
539
+ <div style="width: 100%; height: 900px; margin-top: 10px;">
540
+ <embed
541
+ src="{pdf_url}#toolbar=1&navpanes=0&scrollbar=1&view=FitH"
 
542
  width="100%"
543
+ height="900px"
544
+ type="application/pdf"
545
+ style="border: 1px solid #444; border-radius: 8px;">
 
546
  </div>
547
+ ''', unsafe_allow_html=True)
548
 
549
+ # Fallback viewer options
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550
  st.markdown("---")
551
+ st.markdown("📄 **Alternative viewing options:**")
552
 
553
  col1, col2, col3 = st.columns(3)
554
 
555
  with col1:
556
+ st.markdown(f"[Open in new tab ↗]({pdf_url})")
557
 
558
  with col2:
559
  # PDF.js viewer as backup
560
  pdf_js_url = f"https://mozilla.github.io/pdf.js/web/viewer.html?file={quote(pdf_url, safe='')}"
561
+ st.markdown(f"[Open with PDF viewer ↗]({pdf_js_url})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
562
 
563
  with col3:
564
+ # Direct link
565
+ st.markdown(f"[Direct link]({pdf_url})")
 
566
 
567
+ # If embed doesn't work, show PDF.js viewer as backup
568
+ st.markdown("---")
569
+ st.markdown("🔍 **Backup viewer** (if PDF doesn't display above):")
570
+
571
+ # Use streamlit components for iframe
572
+ import streamlit.components.v1 as components
573
+ components.iframe(
574
+ src=f"https://mozilla.github.io/pdf.js/web/viewer.html?file={quote(pdf_url, safe='')}",
575
+ height=900,
576
+ scrolling=True
577
+ )
578
 
579
  def get_high_accuracy_models(limit=8):
580
  """Get models with highest extraction quality"""