Spaces:
Sleeping
Sleeping
Update app.py
#13
by singhn9 - opened
12345659 unmodified lines6667686970717225 unmodified lines98991001011021031041051061073 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331341352 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701715 unmodified lines1771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433442 unmodified lines3473483493503513523533543553563573583593603613623633643653663673683693703713723 unmodified lines37637737837938038138238338438538638738838939039139228 unmodified lines4214224234244254264276 unmodified lines4344354364374384394404414424434444454464474484494504514524534544554564574584594604614622 unmodified lines4654664674684694704714724734 unmodified lines4784794804814824834844 unmodified lines489490491492493494495# app.py# D3 physics (client-side) + Plotly visualization for MF churn explorer# Option A: Replace Python layout with D3 force simulation in browser# Requirements: gradio, networkx, plotly, pandas, numpyimport gradio as gr59 unmodified linesFRESH_BUY = sanitize_map(FRESH_BUY)# ---------------------------# GRAPH BUILDING# ---------------------------company_edges = []for amc, comps in BUY_MAP.items():25 unmodified linesfor s in sellers:for b in buyers:transfers[(s,b)] += 1edge_list = []for (s,b), w in transfers.items():edge_list.append((s,b, {"action": "transfer", "weight": w}))return edge_listtransfer_edges = infer_amc_transfers(BUY_MAP, SELL_MAP)3 unmodified linesG.add_node(a, type="amc")for c in COMPANIES:G.add_node(c, type="company")for u, v, attrs in company_edges:if u in G.nodes and v in G.nodes:if G.has_edge(u, v):G[u][v]["weight"] += attrs.get("weight",1)G[u][v]["actions"].append(attrs["action"])else:G.add_edge(u, v, weight=attrs.get("weight",1), actions=[attrs["action"]])if include_transfers:for s,b,attrs in transfer_edges:if s in G.nodes and b in G.nodes:if G.has_edge(s,b):G[s][b]["weight"] += attrs.get("weight",1)G[s][b]["actions"].append("transfer")else:G.add_edge(s,b,weight=attrs.get("weight",1), actions=["transfer"])return G# ---------------------------# Build Plotly figure (positions will be set by D3 in browser)# ---------------------------def build_plotly_figure(G,node_color_amc="#9EC5FF",2 unmodified linesedge_color_sell="#d62728",edge_color_transfer="#888888",edge_thickness_base=1.4):# For D3 we don't need Python positions. Use zeros placeholdernode_names = []node_x = []node_y = []node_color = []node_size = []for n, d in G.nodes(data=True):node_names.append(n)node_x.append(0.0)node_y.append(0.0)if d["type"] == "amc":node_color.append(node_color_amc); node_size.append(36)else:node_color.append(node_color_company); node_size.append(56)edge_traces = []edge_source_index = []edge_target_index = []edge_colors = []edge_widths = []for u, v, attrs in G.edges(data=True):# placeholder coordinates, will be updated by D3edge_traces.append(go.Scatter(x=[0,0], y=[0,0], mode="lines",line=dict(color="#888", width=1), hoverinfo="none", opacity=1.0))edge_source_index.append(node_names.index(u))edge_target_index.append(node_names.index(v))acts = attrs.get("actions", [])weight = attrs.get("weight",1)if "complete_exit" in acts:edge_colors.append(edge_color_sell); edge_widths.append(edge_thickness_base*3)5 unmodified linesedge_colors.append(edge_color_sell); edge_widths.append(edge_thickness_base*(1+np.log1p(weight)))else:edge_colors.append(edge_color_buy); edge_widths.append(edge_thickness_base*(1+np.log1p(weight)))node_trace = go.Scatter(x=node_x, y=node_y, mode="markers+text",marker=dict(color=node_color, size=node_size, line=dict(width=2, color="#222")),text=node_names, textposition="top center", hoverinfo="text")fig = go.Figure(data=edge_traces + [node_trace])fig.update_layout(showlegend=False, autosize=True,margin=dict(l=8, r=8, t=36, b=8),xaxis=dict(visible=False), yaxis=dict(visible=False))meta = {"node_names": node_names,"edge_source_index": edge_source_index,"edge_target_index": edge_target_index,"edge_colors": edge_colors,"edge_widths": edge_widths,"node_colors": node_color,"node_sizes": node_size}return fig, metadef make_network_html_d3(fig, meta, div_id="network-plot-div"):"""Build HTML embedding Plotly figure and D3 physics logic.Important: all { and } inside the JS template below are doubled {{ }} so f-string stays valid."""fig_json = json.dumps(fig.to_plotly_json())meta_json = json.dumps(meta)html = f"""<div id="{div_id}" style="width:100%;height:520px;"></div><div style="margin-top:6px;margin-bottom:8px;"><button id="{div_id}-reset" style="padding:8px 12px;border-radius:6px;">Reset view</button><button id="{div_id}-stop" style="padding:8px 12px;border-radius:6px;margin-left:8px;">Stop layout</button></div><!-- load libs --><script src="https://d3js.org/d3.v7.min.js"></script><script src="https://cdn.plot.ly/plotly-latest.min.js"></script><script>// Embed figure and metadataconst fig = {fig_json};const meta = {meta_json};// create plotconst container = document.getElementById("{div_id}");Plotly.newPlot(container, fig.data, fig.layout, {{responsive:true}});// indicesconst nodeTraceIndex = fig.data.length - 1;const edgeCount = fig.data.length - 1;// build nodes array for D3const nodes = meta.node_names.map((n, i) => {{return {{id: i, name: n, r: meta.node_sizes[i] || 20}};}});// build links arrayconst links = meta.edge_source_index.map((s, i) => {{return {{source: s, target: meta.edge_target_index[i], color: meta.edge_colors[i], width: meta.edge_widths[i] || 1}};}});// D3 force simulation parameters tuned for mobile friendlinessconst simulation = d3.forceSimulation(nodes).force("link", d3.forceLink(links).id(d => d.id).distance(130).strength(0.4)).force("charge", d3.forceManyBody().strength(-60)).force("collision", d3.forceCollide().radius(d => d.r * 0.6)).force("center", d3.forceCenter(0,0)).velocityDecay(0.45);// Keep track of whether to keep sim runninglet stopSimulation = false;let lastTickTime = Date.now();let frameSkip = 0;// throttle Plotly updates: update every N ticks for performancelet tickCounter = 0;simulation.on("tick", () => {{tickCounter++;// throttle updates - every 2 ticks (adjustable)if (tickCounter % 2 !== 0) return;// update node coordinates arraysconst xs = nodes.map(n => n.x || 0);const ys = nodes.map(n => n.y || 0);// update node trace positionPlotly.restyle(container, {{ 'x': [xs], 'y': [ys] }}, [nodeTraceIndex]);// update each edge tracefor (let e = 0; e < edgeCount; e++) {{const sIdx = meta.edge_source_index[e];const tIdx = meta.edge_target_index[e];const sx = nodes[sIdx].x || 0;const sy = nodes[sIdx].y || 0;const tx = nodes[tIdx].x || 0;const ty = nodes[tIdx].y || 0;Plotly.restyle(container, {{ 'x': [[sx, tx]], 'y': [[sy, ty]] }}, [e]);}}// stop the simulation gracefully after it's cooledif (simulation.alpha() < 0.03 || stopSimulation) {{simulation.stop();}}}});// allow explicit stopdocument.getElementById("{div_id}-stop").addEventListener('click', () => {{stopSimulation = true;}});// Map node name -> index for click focusconst nameToIndex = {{}};meta.node_names.forEach((n,i) => nameToIndex[n] = i);// focusNode: hides everything except node + neighborsfunction focusNode(nodeName) {{const idx = nameToIndex[nodeName];const keepSet = new Set([idx]);// find neighborsfor (let e = 0; e < meta.edge_source_index.length; e++) {{const s = meta.edge_source_index[e];const t = meta.edge_target_index[e];if (s === idx) keepSet.add(t);if (t === idx) keepSet.add(s);}}// node opacity and label colorsconst N = meta.node_names.length;const nodeOp = Array(N).fill(0.0);const textColors = Array(N).fill("rgba(0,0,0,0)");for (let i = 0; i < N; i++) {{if (keepSet.has(i)) {{nodeOp[i] = 1.0;textColors[i] = "black";}}}}Plotly.restyle(container, {{"marker.opacity": [nodeOp],"textfont.color": [textColors]}}, [nodeTraceIndex]);// edges: show only those connecting kept nodesfor (let e = 0; e < edgeCount; e++) {{const s = meta.edge_source_index[e];const t = meta.edge_target_index[e];const show = keepSet.has(s) && keepSet.has(t);const color = show ? meta.edge_colors[e] : 'rgba(0,0,0,0)';const width = show ? meta.edge_widths[e] : 0.1;Plotly.restyle(container, {{ 'line.color': [color], 'line.width': [width] }}, [e]);}}// zoom to bounding box of kept nodesconst nodesTrace = fig.data[nodeTraceIndex];const xs = [], ys = [];for (let j = 0; j < meta.node_names.length; j++) {{if (keepSet.has(j)) {{xs.push(nodesTrace.x[j]);ys.push(nodesTrace.y[j]);}}}}if (xs.length > 0) {{const xmin = Math.min(...xs), xmax = Math.max(...xs);const ymin = Math.min(...ys), ymax = Math.max(...ys);const padX = (xmax - xmin) * 0.4 + 10;2 unmodified lines}}}}// reset view function: restore everything and restart a short simulation to settlefunction resetView() {{const N = meta.node_names.length;const nodeOp = Array(N).fill(1.0);const textColors = Array(N).fill("black");Plotly.restyle(container, {{ "marker.opacity": [nodeOp], "textfont.color": [textColors] }}, [nodeTraceIndex]);for (let e = 0; e < edgeCount; e++) {{Plotly.restyle(container, {{ 'line.color': [meta.edge_colors[e]], 'line.width': [meta.edge_widths[e]] }}, [e]);}}// autorangePlotly.relayout(container, {{ xaxis: {{autorange:true}}, yaxis: {{autorange:true}} }});// restart a short simulation to re-space nodesstopSimulation = false;simulation.alpha(0.6);simulation.restart();}}// click handler: only react if node trace clickedcontainer.on('plotly_click', function(eventData) {{const p = eventData.points[0];if (p.curveNumber === nodeTraceIndex) {{3 unmodified lines}}}});// reset button hookupdocument.getElementById("{div_id}-reset").addEventListener('click', function() {{resetView();}});</script>"""return html# ---------------------------# Company / AMC inspection helpers (unchanged)# ---------------------------def company_trade_summary(company_name):buyers = [a for a, comps in BUY_MAP.items() if company_name in comps]28 unmodified linesreturn fig, df# ---------------------------# Build the initial HTML (Plotly + D3)# ---------------------------def build_network_html(node_color_company="#FFCF9E", node_color_amc="#9EC5FF",edge_color_buy="#2ca02c", edge_color_sell="#d62728",6 unmodified linesedge_color_sell=edge_color_sell,edge_color_transfer=edge_color_transfer,edge_thickness_base=edge_thickness)return make_network_html_d3(fig, meta)initial_html = build_network_html()# ---------------------------# Mobile CSS and Gradio UI# ---------------------------responsive_css = """.gradio-container { padding:0 !important; margin:0 !important; }.plotly-graph-div, .js-plotly-plot, .output_plot { width:100% !important; max-width:100% !important; }.js-plotly-plot { height:460px !important; }@media(max-width:780px){ .js-plotly-plot{ height:420px !important; } }body, html { overflow-x:hidden !important; }"""with gr.Blocks(css=responsive_css, title="MF Churn Explorer (D3 physics)") as demo:gr.Markdown("## Mutual Fund Churn Explorer — D3 force-directed layout (mobile friendly)")# interactive chart (HTML block)network_html = gr.HTML(value=initial_html)# Legend (updated with inferred note)legend_html = gr.HTML(value="""<div style='font-family:sans-serif;font-size:14px;margin-top:10px;line-height:1.6;'><b>Legend</b><br><div><span style="display:inline-block;width:28px;border-bottom:3px solid #2ca02c;"></span> BUY (green solid)</div>2 unmodified lines<div><span style="display:inline-block;width:28px;border-bottom:5px solid #2ca02c;"></span> FRESH BUY (thick green)</div><div><span style="display:inline-block;width:28px;border-bottom:5px solid #d62728;"></span> COMPLETE EXIT (thick red)</div></div>""")# Controls (unchanged)with gr.Accordion("Network Customization — expand to edit", open=False):node_color_company = gr.ColorPicker("#FFCF9E", label="Company node color")node_color_amc = gr.ColorPicker("#9EC5FF", label="AMC node color")4 unmodified linesinclude_transfers = gr.Checkbox(value=True, label="Show AMC→AMC inferred transfers")update_button = gr.Button("Update Network Graph")# Company & AMC inspect (unchanged)gr.Markdown("### Inspect Company (buyers / sellers)")select_company = gr.Dropdown(choices=COMPANIES, label="Select company")company_plot = gr.Plot()4 unmodified linesamc_plot = gr.Plot()amc_table = gr.DataFrame()# Callbacksdef update_network_html(node_color_company_val, node_color_amc_val,edge_color_buy_val, edge_color_sell_val, edge_color_transfer_val,edge_thickness_val, include_transfers_val):123456759 unmodified lines6768697071727325 unmodified lines991001011021031041051061071083 unmodified lines1121131141151161171181191201211221231241251261271281291301311321331342 unmodified lines1371381391401411421431441451461471481491501511521531541551561571581591601611621631641655 unmodified lines1711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303312 unmodified lines3343353363373383393403413423433443453463473483493503513523533543553563 unmodified lines36036136236336436536636736836937037137237337437528 unmodified lines4044054064074084094106 unmodified lines4174184194204214224234244254264274284294304314324334344354364374384394404414424432 unmodified lines4464474484494504514524534 unmodified lines4584594604614624634 unmodified lines468469470471472473# app.py# D3 physics (client-side) + Plotly visualization for MF churn explorer# Liquid "gel" motion (viscous, slow, ooze-like) - Option L2# Requirements: gradio, networkx, plotly, pandas, numpyimport gradio as gr59 unmodified linesFRESH_BUY = sanitize_map(FRESH_BUY)# ---------------------------# BUILD GRAPH# ---------------------------company_edges = []for amc, comps in BUY_MAP.items():25 unmodified linesfor s in sellers:for b in buyers:transfers[(s,b)] += 1out = []for (s,b), w in transfers.items():out.append((s,b, {"action":"transfer","weight":w}))return outtransfer_edges = infer_amc_transfers(BUY_MAP, SELL_MAP)3 unmodified linesG.add_node(a, type="amc")for c in COMPANIES:G.add_node(c, type="company")for u,v,attr in company_edges:if G.has_edge(u,v):G[u][v]["weight"] += attr["weight"]G[u][v]["actions"].append(attr["action"])else:G.add_edge(u,v,weight=attr["weight"], actions=[attr["action"]])if include_transfers:for s,b,attr in transfer_edges:if G.has_edge(s,b):G[s][b]["weight"] += attr["weight"]G[s][b]["actions"].append("transfer")else:G.add_edge(s,b,weight=attr["weight"], actions=["transfer"])return G# ---------------------------# BUILD PLOTLY FIGURE (placeholders for positions)# ---------------------------def build_plotly_figure(G,node_color_amc="#9EC5FF",2 unmodified linesedge_color_sell="#d62728",edge_color_transfer="#888888",edge_thickness_base=1.4):node_names = []node_x = []node_y = []node_color = []node_size = []for n,d in G.nodes(data=True):node_names.append(n)node_x.append(0.0); node_y.append(0.0)if d["type"]=="amc":node_color.append(node_color_amc); node_size.append(36)else:node_color.append(node_color_company); node_size.append(56)edge_traces = []edge_src = []edge_tgt = []edge_colors = []edge_widths = []for u,v,attrs in G.edges(data=True):edge_traces.append(go.Scatter(x=[0,0], y=[0,0], mode="lines",line=dict(color="#888", width=1), hoverinfo="none"))edge_src.append(node_names.index(u))edge_tgt.append(node_names.index(v))acts = attrs.get("actions",[])weight = attrs.get("weight",1)if "complete_exit" in acts:edge_colors.append(edge_color_sell); edge_widths.append(edge_thickness_base*3)5 unmodified linesedge_colors.append(edge_color_sell); edge_widths.append(edge_thickness_base*(1+np.log1p(weight)))else:edge_colors.append(edge_color_buy); edge_widths.append(edge_thickness_base*(1+np.log1p(weight)))node_trace = go.Scatter(x=node_x, y=node_y, mode="markers+text",marker=dict(color=node_color, size=node_size, line=dict(width=2,color="#222")),text=node_names, textposition="top center", hoverinfo="text")fig = go.Figure(data=edge_traces + [node_trace])fig.update_layout(showlegend=False, autosize=True,margin=dict(l=8,r=8,t=36,b=8), xaxis=dict(visible=False), yaxis=dict(visible=False))meta = {"node_names": node_names,"edge_source_index": edge_src,"edge_target_index": edge_tgt,"edge_colors": edge_colors,"edge_widths": edge_widths,"node_sizes": node_size}return fig, meta# ---------------------------# Build HTML with D3 + viscous "gel" motion# ---------------------------def make_network_html_d3_gel(fig, meta, div_id="network-plot-div"):fig_json = json.dumps(fig.to_plotly_json())meta_json = json.dumps(meta)html = f"""<div id="{div_id}" style="width:100%;height:560px;"></div><div style="margin-top:6px;margin-bottom:8px;"><button id="{div_id}-reset" style="padding:8px 12px;border-radius:6px;">Reset view</button><button id="{div_id}-stop" style="padding:8px 12px;border-radius:6px;margin-left:8px;">Stop layout</button></div><script src="https://d3js.org/d3.v7.min.js"></script><script src="https://cdn.plot.ly/plotly-latest.min.js"></script><script>const fig = {fig_json};const meta = {meta_json};const container = document.getElementById("{div_id}");Plotly.newPlot(container, fig.data, fig.layout, {{responsive:true}});// index bookkeepingconst nodeTraceIndex = fig.data.length - 1;const edgeCount = fig.data.length - 1;// build nodes and links for D3const nodes = meta.node_names.map((n,i)=>({{id:i, name:n, r: meta.node_sizes[i] || 20}}));const links = meta.edge_source_index.map((s,i)=>({{source:s, target: meta.edge_target_index[i], color: meta.edge_colors[i], width: meta.edge_widths[i] || 1}}));// Viscous gel simulation parameters (softer, slower motion)const simulation = d3.forceSimulation(nodes).force("link", d3.forceLink(links).id(d => d.id).distance(140).strength(0.35)).force("charge", d3.forceManyBody().strength(-40)).force("collision", d3.forceCollide().radius(d => d.r * 0.85)).force("center", d3.forceCenter(0,0)).velocityDecay(0.55);// We add per-node velocity smoothing variables to create "gel" feelnodes.forEach(n => {{n.vx_smooth = 0;n.vy_smooth = 0;n.displayX = n.x || 0;n.displayY = n.y || 0;}});let tickCount = 0;const maxTicks = 400; // safety capsimulation.on("tick", () => {{tickCount++;// On each tick, update the target positions from d3, then apply viscous smoothingnodes.forEach(n => {{// D3 provides n.x/n.y; we do gel smoothing on displayX/displayY using velocityconst targetX = n.x || 0;const targetY = n.y || 0;// viscous velocity update (gel-like): vx_smooth integrates difference slowlyn.vx_smooth = (n.vx_smooth * 0.82) + (targetX - n.displayX) * 0.06;n.vy_smooth = (n.vy_smooth * 0.82) + (targetY - n.displayY) * 0.06;// apply a small damping to give heavy 'gel' inertian.vx_smooth *= 0.92;n.vy_smooth *= 0.92;// update display positionsn.displayX += n.vx_smooth;n.displayY += n.vy_smooth;}});// prepare arrays for Plotly update using displayX/displayYconst xs = nodes.map(n => n.displayX);const ys = nodes.map(n => n.displayY);// update node tracePlotly.restyle(container, {{ 'x': [xs], 'y': [ys] }}, [nodeTraceIndex]);// update each edge trace using display positionsfor (let e = 0; e < edgeCount; e++) {{const sIdx = meta.edge_source_index[e];const tIdx = meta.edge_target_index[e];const sx = nodes[sIdx].displayX || 0;const sy = nodes[sIdx].displayY || 0;const tx = nodes[tIdx].displayX || 0;const ty = nodes[tIdx].displayY || 0;Plotly.restyle(container, {{ 'x': [[sx, tx]], 'y': [[sy, ty]] }}, [e]);// set line style color/width (ensure visual matches original meta)Plotly.restyle(container, {{ 'line.color': [meta.edge_colors[e]], 'line.width': [meta.edge_widths[e]] }}, [e]);}}// Safety stop conditionsif (simulation.alpha() < 0.02 || tickCount > maxTicks) {{simulation.stop();}}}});// stop buttondocument.getElementById("{div_id}-stop").addEventListener('click', () => {{simulation.stop();}});// map name to indexconst nameToIndex = {{}};meta.node_names.forEach((n,i)=> nameToIndex[n]=i);// focus and reset functions (hide others on focus - Option A)function focusNode(nodeName) {{const idx = nameToIndex[nodeName];const keep = new Set([idx]);for (let e = 0; e < meta.edge_source_index.length; e++) {{const s = meta.edge_source_index[e], t = meta.edge_target_index[e];if (s === idx) keep.add(t);if (t === idx) keep.add(s);}}const N = meta.node_names.length;const nodeOp = Array(N).fill(0.0);const textColors = Array(N).fill("rgba(0,0,0,0)");for (let i=0;i<N;i++) {{if (keep.has(i)) {{ nodeOp[i]=1.0; textColors[i]="black"; }}}}Plotly.restyle(container, {{ "marker.opacity": [nodeOp], "textfont.color": [textColors] }}, [nodeTraceIndex]);// edgesfor (let e=0;e<edgeCount;e++) {{const s = meta.edge_source_index[e], t = meta.edge_target_index[e];const show = keep.has(s) && keep.has(t);const color = show ? meta.edge_colors[e] : 'rgba(0,0,0,0)';const width = show ? meta.edge_widths[e] : 0.1;Plotly.restyle(container, {{ 'line.color': [color], 'line.width': [width] }}, [e]);}}// zoom to bboxconst nodesTrace = fig.data[nodeTraceIndex];const xs = [], ys = [];for (let j=0;j<meta.node_names.length;j++) {{if (keep.has(j)) {{ xs.push(nodesTrace.x[j]); ys.push(nodesTrace.y[j]); }}}}if (xs.length>0) {{const xmin = Math.min(...xs), xmax = Math.max(...xs);const ymin = Math.min(...ys), ymax = Math.max(...ys);const padX = (xmax - xmin) * 0.4 + 10;2 unmodified lines}}}}// resetfunction resetView() {{const N = meta.node_names.length;const nodeOp = Array(N).fill(1.0);const textColors = Array(N).fill("black");Plotly.restyle(container, {{ "marker.opacity": [nodeOp], "textfont.color": [textColors] }}, [nodeTraceIndex]);for (let e=0;e<edgeCount;e++) {{Plotly.restyle(container, {{ 'line.color': [meta.edge_colors[e]], 'line.width': [meta.edge_widths[e]] }}, [e]);}}Plotly.relayout(container, {{ xaxis: {{autorange:true}}, yaxis: {{autorange:true}} }});// restart a gentle simulation to re-space nodestickCount = 0;simulation.alpha(0.5);simulation.restart();}}// click handlercontainer.on('plotly_click', function(eventData) {{const p = eventData.points[0];if (p.curveNumber === nodeTraceIndex) {{3 unmodified lines}}}});// reset buttondocument.getElementById("{div_id}-reset").addEventListener('click', function() {{resetView();}});</script>"""return html# ---------------------------# Company / AMC summaries (unchanged)# ---------------------------def company_trade_summary(company_name):buyers = [a for a, comps in BUY_MAP.items() if company_name in comps]28 unmodified linesreturn fig, df# ---------------------------# Build initial HTML# ---------------------------def build_network_html(node_color_company="#FFCF9E", node_color_amc="#9EC5FF",edge_color_buy="#2ca02c", edge_color_sell="#d62728",6 unmodified linesedge_color_sell=edge_color_sell,edge_color_transfer=edge_color_transfer,edge_thickness_base=edge_thickness)return make_network_html_d3_gel(fig, meta)initial_html = build_network_html()# ---------------------------# Mobile CSS & UI# ---------------------------responsive_css = """.gradio-container { padding:0 !important; margin:0 !important; }.plotly-graph-div, .js-plotly-plot, .output_plot { width:100% !important; max-width:100% !important; }.js-plotly-plot { height:560px !important; }@media(max-width:780px){ .js-plotly-plot{ height:520px !important; } }body, html { overflow-x:hidden !important; }"""with gr.Blocks(css=responsive_css, title="MF Churn Explorer (Gel Motion)") as demo:gr.Markdown("## Mutual Fund Churn Explorer — Gel-like liquid motion (L2)")network_html = gr.HTML(value=initial_html)legend_html = gr.HTML(value=\"\"\"<div style='font-family:sans-serif;font-size:14px;margin-top:10px;line-height:1.6;'><b>Legend</b><br><div><span style="display:inline-block;width:28px;border-bottom:3px solid #2ca02c;"></span> BUY (green solid)</div>2 unmodified lines<div><span style="display:inline-block;width:28px;border-bottom:5px solid #2ca02c;"></span> FRESH BUY (thick green)</div><div><span style="display:inline-block;width:28px;border-bottom:5px solid #d62728;"></span> COMPLETE EXIT (thick red)</div></div>\"\"\")with gr.Accordion("Network Customization — expand to edit", open=False):node_color_company = gr.ColorPicker("#FFCF9E", label="Company node color")node_color_amc = gr.ColorPicker("#9EC5FF", label="AMC node color")4 unmodified linesinclude_transfers = gr.Checkbox(value=True, label="Show AMC→AMC inferred transfers")update_button = gr.Button("Update Network Graph")gr.Markdown("### Inspect Company (buyers / sellers)")select_company = gr.Dropdown(choices=COMPANIES, label="Select company")company_plot = gr.Plot()4 unmodified linesamc_plot = gr.Plot()amc_table = gr.DataFrame()def update_network_html(node_color_company_val, node_color_amc_val,edge_color_buy_val, edge_color_sell_val, edge_color_transfer_val,edge_thickness_val, include_transfers_val):
app.py+128-150