simple-text-analyzer / diagnose_upload_error.py
egumasa's picture
added memory file handler
4b36911
"""
Diagnostic script for file upload 403 errors
"""
import streamlit as st
import os
import tempfile
import traceback
from pathlib import Path
st.set_page_config(page_title="Upload Diagnostic", layout="wide")
st.title("File Upload Diagnostic Tool")
st.write("This tool helps diagnose file upload issues and 403 errors")
# Check environment
st.subheader("1. Environment Check")
col1, col2 = st.columns(2)
with col1:
st.write("**System Info:**")
st.write(f"- Platform: {os.name}")
st.write(f"- Python: {os.sys.version.split()[0]}")
st.write(f"- Streamlit: {st.__version__}")
st.write(f"- Working Dir: {os.getcwd()}")
with col2:
st.write("**Temp Directory:**")
st.write(f"- Temp Dir: {tempfile.gettempdir()}")
st.write(f"- Writable: {os.access(tempfile.gettempdir(), os.W_OK)}")
# Check disk space
try:
stat = os.statvfs(tempfile.gettempdir())
free_mb = (stat.f_frsize * stat.f_bavail) / (1024 * 1024)
st.write(f"- Free Space: {free_mb:.1f} MB")
except:
st.write("- Free Space: Unknown")
# File upload test
st.subheader("2. File Upload Test")
uploaded_file = st.file_uploader(
"Upload a test file",
type=['txt', 'csv', 'tsv'],
help="Upload any file to test"
)
if uploaded_file:
st.write("**File received by Streamlit:**")
st.write(f"- Name: {uploaded_file.name}")
st.write(f"- Type: {uploaded_file.type}")
st.write(f"- Size: {uploaded_file.size} bytes")
# Test different read methods
st.subheader("3. Testing Read Methods")
# Method 1: Direct read
with st.expander("Method 1: Direct read()"):
try:
uploaded_file.seek(0)
content = uploaded_file.read()
st.success(f"βœ… Success! Read {len(content)} bytes")
st.code(content[:200].decode('utf-8', errors='ignore') + "...")
except Exception as e:
st.error(f"❌ Failed: {type(e).__name__}: {str(e)}")
st.code(traceback.format_exc())
# Method 2: getvalue()
with st.expander("Method 2: getvalue()"):
try:
uploaded_file.seek(0)
content = uploaded_file.getvalue()
st.success(f"βœ… Success! Read {len(content)} bytes")
st.code(content[:200].decode('utf-8', errors='ignore') + "...")
except Exception as e:
st.error(f"❌ Failed: {type(e).__name__}: {str(e)}")
st.code(traceback.format_exc())
# Method 3: getbuffer()
with st.expander("Method 3: getbuffer()"):
try:
uploaded_file.seek(0)
content = uploaded_file.getbuffer()
st.success(f"βœ… Success! Buffer size: {len(content)} bytes")
st.code(str(content[:200]))
except Exception as e:
st.error(f"❌ Failed: {type(e).__name__}: {str(e)}")
st.code(traceback.format_exc())
# Method 4: Save to temp
with st.expander("Method 4: Save to temp file"):
try:
# Try different temp locations
temp_locations = [
("/tmp", "System /tmp"),
(tempfile.gettempdir(), "Python tempdir"),
(".", "Current directory"),
(str(Path.home() / ".streamlit" / "temp"), "Streamlit temp")
]
for temp_dir, desc in temp_locations:
st.write(f"\n**Trying {desc}: {temp_dir}**")
if not os.path.exists(temp_dir):
try:
os.makedirs(temp_dir, exist_ok=True)
st.write(f"βœ… Created directory")
except:
st.write(f"❌ Cannot create directory")
continue
if not os.access(temp_dir, os.W_OK):
st.write(f"❌ Not writable")
continue
try:
temp_path = os.path.join(temp_dir, f"test_{uploaded_file.name}")
with open(temp_path, 'wb') as f:
uploaded_file.seek(0)
f.write(uploaded_file.getbuffer())
if os.path.exists(temp_path):
size = os.path.getsize(temp_path)
st.success(f"βœ… Saved successfully! Size: {size} bytes")
st.code(f"Path: {temp_path}")
# Try to read back
with open(temp_path, 'rb') as f:
content = f.read()
st.write(f"βœ… Read back: {len(content)} bytes")
# Cleanup
os.remove(temp_path)
st.write("βœ… Cleaned up")
break
else:
st.error("❌ File not found after saving")
except Exception as e:
st.error(f"❌ Failed: {type(e).__name__}: {str(e)}")
if "403" in str(e):
st.error("**403 ERROR DETECTED!**")
st.code(traceback.format_exc())
except Exception as e:
st.error(f"❌ General failure: {str(e)}")
st.code(traceback.format_exc())
# Network test
st.subheader("4. Network Configuration")
st.write("**Streamlit Server Config:**")
st.write(f"- Server Port: {os.environ.get('STREAMLIT_SERVER_PORT', '8501')}")
st.write(f"- Server Address: {os.environ.get('STREAMLIT_SERVER_ADDRESS', 'Not set')}")
st.write(f"- Browser Port: {os.environ.get('STREAMLIT_BROWSER_SERVER_PORT', 'Not set')}")
# Check for proxy
proxy_vars = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy']
for var in proxy_vars:
if var in os.environ:
st.write(f"- {var}: {os.environ[var]}")
st.info("If you see a 403 error above, please share the full error message and traceback.")