Spaces:
Sleeping

finaltvs / streamlit_app.py
rbachina's picture
Update streamlit_app.py
69576af verified
Raw History Blame Contribute Delete
23.2 kB
import streamlit as st
import asyncio
from playwright.async_api import async_playwright, TimeoutError as PWTimeoutError
from PIL import Image
import io
import os
from typing import Optional, Dict, Any, List
st.set_page_config(page_title="TVSnapper Tester", layout="wide")
TV_SELECTORS: List[str] = [
"#tv_chart_container",
"div[data-name='chart-container']",
"div[class*='chart-container']",
"div[class*='chartContainer']",
"div[class*='js-rootresizer__contents']",
"div[class*='tv-chart-view']",
"div[class*='chart-page']",
]
# Minimal CSS to hide obvious UI elements without hitting the chart
# Applied only in Page mode - Snapshot mode (Alt+S) already provides clean output
HIDE_TV_CSS = '''
/* --- POPUPS & MODALS --- */
[role="dialog"],
div[class*="tv-dialog"],
div[class*="gopro-"],
div[class*="paywall"],
div[class*="trial"],
div[class*="subscription"],
div[class*="popup"]:not([class*="chart"]):not([id*="chart"]) {
display:none !important; visibility:hidden !important; opacity:0 !important;
}
/* --- SIDEBARS (Safe Selectors) --- */
/* Hide the right-hand widget sidebar */
div[class*="widgetbar"]:not([class*="chart"]),
div[class*="right-toolbar"]:not([class*="chart"]),
div[data-role="right-toolbar"],
aside[class*="sidebar"] {
display:none !important; visibility:hidden !important; opacity:0 !important;
}
/* --- HEADERS (Safe Selectors) --- */
/* Hide top navigation headers */
header:not([class*="chart"]),
div[class*="header"]:not([class*="chart"]):not([id*="chart"]):not([class*="pane"]),
div[class*="topbar"]:not([class*="chart"]) {
display:none !important; visibility:hidden !important; opacity:0 !important;
}
/* --- TRADINGVIEW SPECIFIC --- */
/* Hide floating drawing toolbars if possible, but be careful */
div[class*="drawing-toolbar"],
div[data-role="drawing-toolbar"] {
display:none !important; visibility:hidden !important; opacity:0 !important;
}
/* Hide legend if user wants pure chart (optional, usually kept but can start clutter) */
/* div[data-name="legend"] { display:none !important; } */
'''
def filename_exists(name):
return os.path.exists(name)
def crop_png(png_bytes: bytes, box: Dict[str, float], pad: int = 8) -> bytes:
img = Image.open(io.BytesIO(png_bytes)).convert("RGBA")
left = max(int(box["x"]) - pad, 0)
top = max(int(box["y"]) - pad, 0)
right = min(int(box["x"] + box["width"]) + pad, img.width)
bottom = min(int(box["y"] + box["height"]) + pad, img.height)
cropped = img.crop((left, top, right, bottom))
out = io.BytesIO()
cropped.save(out, format="PNG")
return out.getvalue()
async def find_best_bbox(page) -> Optional[Dict[str, Any]]:
best = None
for sel in TV_SELECTORS:
try:
loc = page.locator(sel).first
if await loc.count() == 0:
continue
box = await loc.bounding_box()
if not box:
continue
w, h = box.get("width", 0), box.get("height", 0)
if w < 600 or h < 300:
continue
area = w * h
if best is None or area > best["area"]:
best = {"selector": sel, "box": box, "area": area}
except Exception:
continue
return best
async def best_effort_close_popups(page) -> None:
# ESC often closes dialogs
try:
await page.keyboard.press("Escape")
except Exception:
pass
# selectors for various close buttons
close_selectors = [
"button[aria-label='Close']",
"button[title='Close']",
"div[role='dialog'] button[class*='close']",
"div[class*='tv-dialog'] button",
"svg[class*='close-']", # Click SVGs that look like close icons
"[data-name='close']",
".close, .tv-dialog__close, .popupDialogButtonClose",
]
for sel in close_selectors:
try:
# Try clicking multiple times if there are multiple overlays
buttons = page.locator(sel)
count = await buttons.count()
for i in range(count):
if await buttons.nth(i).is_visible():
await buttons.nth(i).click(timeout=500)
await page.wait_for_timeout(200)
except Exception:
continue
# Explicitly try to close Gopro/Trial popups by finding "Maybe later", "NO" buttons
# Also handles the "See what others don't" popup which often has an X button in a specific container
deny_text_selectors = ["text=Maybe later", "text=No thanks", "text=Cancel", "button[class*='close-button']"]
for txt in deny_text_selectors:
try:
btn = page.locator(txt).first
if await btn.is_visible():
await btn.click(timeout=500)
except Exception:
pass
async def wait_for_chart_stable(page, ms: int) -> None:
await page.wait_for_timeout(ms)
async def wait_for_indicators(page, max_wait_ms: int = 30000) -> bool:
"""
Wait for TradingView indicators to load by checking for canvas updates.
Returns True if indicators appear loaded, False if timeout.
"""
start_time = asyncio.get_event_loop().time()
while (asyncio.get_event_loop().time() - start_time) * 1000 < max_wait_ms:
try:
# Check if multiple canvas elements exist (indicates indicators loaded)
canvas_count = await page.locator("canvas").count()
if canvas_count > 2: # Main chart + at least one indicator
# Additional wait for rendering to complete
await page.wait_for_timeout(2000)
return True
except Exception:
pass
await page.wait_for_timeout(1000) # Check every second
return False # Timeout - indicators may not have loaded
async def capture_snapshot_trigger(page, trigger_method: str, snap_wait_ms: int, max_wait_newtab_ms: int) -> tuple[Any, bool]:
"""
Triggers the snapshot action via Keyboard (Alt+S) or UI Click.
Returns (page, is_new_tab).
"""
if trigger_method == "keyboard":
# Press Alt+S (TradingView Snapshot shortcut)
# Using AltLeft as per working Node.js implementation
await page.keyboard.down("AltLeft")
await page.keyboard.press("S")
await page.keyboard.up("AltLeft")
elif trigger_method == "click":
# 1. Click the Camera Icon
try:
# Selector provided by user: id="header-toolbar-screenshot"
toolbar_btn = page.locator("#header-toolbar-screenshot")
if await toolbar_btn.is_visible():
print("Clicking Toolbar Screenshot button...")
await toolbar_btn.click()
await page.wait_for_timeout(1000) # Wait for menu
# 2. Click the 'Open image in new tab' or 'Copy link' item from dropdown
# We need to find the specific menu item.
# Common data-names: 'save-chart-image', 'open-image-in-new-tab', 'copy-link-to-the-chart-image'
# Let's try to click one that generates a link/tab
menu_items = [
"div[data-name='open-image-in-new-tab']",
"div[data-name='save-chart-image']", # Sometimes downloads, sometimes opens tab
"div[data-name='copy-link-to-the-chart-image']" # Might just copy to clipboard
]
clicked_menu = False
for item in menu_items:
try:
menu_opt = page.locator(item)
if await menu_opt.count() > 0 and await menu_opt.is_visible():
print(f"Clicking menu item: {item}")
await menu_opt.click()
clicked_menu = True
break
except:
continue
if not clicked_menu:
print("Could not find a suitable menu item to click after opening toolbar.")
except Exception as e:
print(f"Toolbar click trigger failed: {e}")
# Wait for new tab (Common for both methods)
is_new_tab = False
try:
new_page = await page.context.wait_for_event("page", timeout=max_wait_newtab_ms)
is_new_tab = True
except PWTimeoutError:
new_page = page
try:
await new_page.bring_to_front()
except Exception:
pass
try:
await new_page.wait_for_load_state("domcontentloaded", timeout=60000)
except Exception:
pass
await new_page.wait_for_timeout(snap_wait_ms)
return new_page, is_new_tab
async def login_and_save_state(browser, username, password, user_agent, nav_timeout):
"""
Logs in to TradingView and saves storage state (cookies/local storage) to disk.
Returns the path to the saved state file.
"""
page = await browser.new_page(user_agent=user_agent or None)
page.set_default_navigation_timeout(nav_timeout)
try:
# Check if already logged in (if we reused context, but here we usually start fresh or check existing)
await page.goto("https://www.tradingview.com/", wait_until="domcontentloaded")
# Look for user menu or avatar indicating logged in state
is_logged_in = False
try:
# This selector targets the user profile picture/menu in header
if await page.locator("div[data-role='header-user-menu-button']").count() > 0:
is_logged_in = True
except:
pass
if not is_logged_in:
print("Logging in...")
await page.goto("https://www.tradingview.com/accounts/signin/", wait_until="domcontentloaded")
# Click Email button if present (sometimes it defaults to social)
try:
email_btn = page.locator("button[name='Email']")
if await email_btn.is_visible():
await email_btn.click()
except:
pass
# Fill credentials
await page.fill("input[name='username']", username)
await page.fill("input[name='password']", password)
await page.click("button[type='submit']")
# Wait for login to complete (redirect to home or user element appearing)
# Give user time to solve CAPTCHA if needed (headless=False helps here)
await page.wait_for_selector("div[data-role='header-user-menu-button']", timeout=60000)
# Save state
await page.context.storage_state(path="tradingview_state.json")
await page.close()
return "tradingview_state.json"
except Exception as e:
print(f"Login failed: {e}")
await page.close()
return None
async def capture(url: str,
capture_mode: str,
width: int,
height: int,
wait_until: str,
nav_timeout_ms: int,
chart_wait_ms: int,
snap_wait_ms: int,
indicator_wait_ms: int,
pad: int,
user_agent: Optional[str],
block_media: bool,
apply_hide_css: bool,
close_popups: bool,
max_wait_newtab_ms: int,
crop_chart: bool,
username: Optional[str] = None,
password: Optional[str] = None,
click_toolbar_button: bool = False,
manual_sessionid: Optional[str] = None,
manual_sessionid_sign: Optional[str] = None) -> tuple[bytes, Dict[str, Any]]:
st.sidebar.markdown("---")
headless_mode = st.sidebar.checkbox("Headless Mode (Hidden Browser)", value=True, help="Uncheck this if snapshots are failing. Seeing the browser often helps bypass bot detection.")
async with async_playwright() as p:
# Args copied from working Node.js implementation
browser_args = [
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-gpu",
"--start-fullscreen",
"--disable-web-security",
"--disable-features=IsolateOrigins,site-per-process",
"--disable-site-isolation-trials",
"--disable-features=BlockInsecurePrivateNetworkRequests",
"--disable-infobars"
]
browser = await p.chromium.launch(
headless=headless_mode,
args=browser_args,
)
# STORAGE STATE MANAGEMENT
storage_state_path = "tradingview_state.json"
context_created = False
# 1. Try to use existing state file first
if filename_exists(storage_state_path):
try:
context = await browser.new_context(
storage_state=storage_state_path,
viewport={"width": width, "height": height},
user_agent=user_agent or None,
)
context_created = True
except:
pass
# 2. If no context yet, and we have credentials, perform login to generate state
if not context_created and username and password:
state_file = await login_and_save_state(browser, username, password, user_agent, nav_timeout_ms)
if state_file:
context = await browser.new_context(
storage_state=state_file,
viewport={"width": width, "height": height},
user_agent=user_agent or None,
)
context_created = True
# 3. Fallback to fresh context
if not context_created:
context = await browser.new_context(
viewport={"width": width, "height": height},
user_agent=user_agent or None,
)
# INJECT MANUAL SESSION COOKIES (Override/Add to current context)
if manual_sessionid and manual_sessionid_sign:
print("Injecting manual session cookies...")
await context.add_cookies([
{
"name": "sessionid",
"value": manual_sessionid,
"domain": ".tradingview.com",
"path": "/"
},
{
"name": "sessionid_sign",
"value": manual_sessionid_sign,
"domain": ".tradingview.com",
"path": "/"
}
])
page = await context.new_page()
page.set_default_navigation_timeout(nav_timeout_ms)
page.set_default_timeout(nav_timeout_ms)
if block_media:
await page.route("**/*", lambda route: route.abort()
if route.request.resource_type in ["image", "media", "font"]
else route.continue_())
try:
await page.goto(url, wait_until=wait_until)
except Exception as e:
print(f"Navigation error: {e}")
pass
# Only apply CSS hiding in Page mode (and fallback)
if apply_hide_css and capture_mode != "Snapshot (Alt+S)":
try:
await page.add_style_tag(content=HIDE_TV_CSS)
except Exception:
pass
# Try to close popups if requested
if close_popups:
await best_effort_close_popups(page)
# Wait for indicators if configured
if indicator_wait_ms > 0:
indicators_loaded = await wait_for_indicators(page, indicator_wait_ms)
else:
indicators_loaded = False
if capture_mode == "Snapshot (Alt+S)":
# Additional wait for chart stability before snapshot
await wait_for_chart_stable(page, chart_wait_ms)
# Determine Trigger Method
trigger = "click" if click_toolbar_button else "keyboard"
target_page, is_new_tab = await capture_snapshot_trigger(
page=page,
trigger_method=trigger,
snap_wait_ms=snap_wait_ms,
max_wait_newtab_ms=max_wait_newtab_ms,
)
# If Trigger failed (no new tab), we are on the main page.
# We MUST apply CSS and try to close popups again because we skipped it earlier.
if not is_new_tab:
if apply_hide_css:
try:
await target_page.add_style_tag(content=HIDE_TV_CSS)
except Exception:
pass
if close_popups:
await best_effort_close_popups(target_page)
# Wait a bit for CSS/Popups to clear
await target_page.wait_for_timeout(1000)
png = await target_page.screenshot(full_page=True, type="png")
else:
await wait_for_chart_stable(page, chart_wait_ms)
# If user wanted to click the toolbar button in Page Mode for some reason (rare, but honoring the flag)
# This handles the "Page Layout" capture but with the snapshot menu open?
# Actually, user likely meant Snapshot Mode. But if flag is set here, let's just do it.
if click_toolbar_button:
# Just click and wait (maybe capturing the menu?)
try:
await page.click("#header-toolbar-screenshot")
await page.wait_for_timeout(1000)
except:
pass
if crop_chart:
best = await find_best_bbox(page)
viewport_png = await page.screenshot(full_page=False, type="png")
png = crop_png(viewport_png, best["box"], pad=pad) if best and best.get("box") else viewport_png
else:
png = await page.screenshot(full_page=True, type="png")
await context.close()
await browser.close()
status = {
"indicators_loaded": indicators_loaded,
"capture_mode": capture_mode,
"snapshot_success": locals().get("is_new_tab", False) if capture_mode == "Snapshot (Alt+S)" else None
}
return png, status
st.title("📸 TVSnapper – Streamlit Tester")
st.caption("Goal: chart-only screenshot with indicators loaded. Use **Snapshot (Alt+S)** for best results.")
with st.sidebar:
st.header("Input")
url = st.text_input("URL", value="https://www.tradingview.com/chart/T1QfifTV/")
st.header("Premium Login (Optional)")
st.caption("Log in to remove ads/popups and load Pro indicators.")
username = st.text_input("Username / Email")
password = st.text_input("Password", type="password")
if os.path.exists("tradingview_state.json"):
st.success("✅ Saved session found. Will try to use it.")
if st.button("Clear Saved Session"):
try:
os.remove("tradingview_state.json")
st.rerun()
except:
pass
st.caption("OR: Manually enter Cookies (Developer Tools -> Application -> Cookies)")
manual_sid = st.text_input("sessionid (cookie)", type="password")
manual_sid_sign = st.text_input("sessionid_sign (cookie)", type="password")
st.header("Capture")
capture_mode = st.selectbox("Capture mode", ["Snapshot Mode (New Tab)", "Page (crop chart)"], index=0)
st.header("Viewport")
width = st.number_input("Width", min_value=800, max_value=4000, value=1600, step=50)
height = st.number_input("Height", min_value=600, max_value=3000, value=900, step=50)
# ... (Timing section skipped for brevity) ...
st.header("Options")
apply_hide_css = st.checkbox("Hide popups via CSS (Page mode only)", value=True)
close_popups = st.checkbox("Try to close popups (ESC + close buttons)", value=True)
click_toolbar_button = st.checkbox("Trigger via Toolbar Button (No Alt+S)", value=True, help="Clicks camera icon instead of using Alt+S shortcut.")
crop_chart = st.checkbox("Crop to chart container (Page mode)", value=True)
pad = st.number_input("Crop padding (px)", min_value=0, max_value=100, value=8, step=1)
block_media = st.checkbox("Block media (video/audio)", value=True)
user_agent = st.text_input("User-Agent (optional)", value="")
run = st.button("Generate Screenshot", type="primary")
if run:
if not url.strip():
st.error("URL is required.")
else:
with st.spinner("Opening page and capturing screenshot…"):
try:
png, status = asyncio.run(
capture(
url=url.strip(),
capture_mode=capture_mode,
width=int(width),
height=int(height),
wait_until=wait_until,
nav_timeout_ms=int(nav_timeout_ms),
chart_wait_ms=int(chart_wait_ms),
snap_wait_ms=int(snap_wait_ms),
indicator_wait_ms=int(indicator_wait_ms),
pad=int(pad),
user_agent=user_agent.strip() or None,
block_media=bool(block_media),
apply_hide_css=bool(apply_hide_css),
close_popups=bool(close_popups),
max_wait_newtab_ms=int(max_wait_newtab_ms),
crop_chart=bool(crop_chart),
username=username.strip() if username else None,
password=password.strip() if password else None,
click_toolbar_button=bool(click_toolbar_button),
manual_sessionid=manual_sid.strip() if manual_sid else None,
manual_sessionid_sign=manual_sid_sign.strip() if manual_sid_sign else None,
)
)
# Display status feedback
if status.get("indicators_loaded"):
st.success("Done ✅ - Indicators detected and loaded")
else:
st.warning("Done ⚠️ - Screenshot captured but indicators may not have fully loaded. Try increasing 'Wait for indicators' time.")
if status.get("capture_mode") == "Snapshot Mode (New Tab)" and status.get("snapshot_success") is False:
st.info("ℹ️ Snapshot mode didn't open a new tab. Captured main page with CSS hiding applied instead.")
st.image(png, use_column_width=True)
st.download_button("Download PNG", png, file_name="tvsnapper.png", mime="image/png")
except Exception as e:
st.error(f"Failed: {e}")