File size: 6,295 Bytes
1fc95c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
"""
Subscription Audit β€” main Gradio app for Hugging Face Spaces.

Free public tool. Paste a bank statement CSV, get a categorized audit of
recurring subscriptions with cancel-this-now flags and shareable summary.

Deploy: huggingface.co/spaces/ledgerlaunchco/subscription-audit
"""

from __future__ import annotations
import gradio as gr
import pandas as pd
import tempfile

from detector import parse_bank_csv, detect_subscriptions
from share_graphic import generate_summary_image, generate_warning_image
from ctas import render_full_cta_stack, render_empty_state_cta


def _detected_to_dataframe(detected) -> pd.DataFrame:
    if not detected:
        return pd.DataFrame()
    rows = []
    for s in detected:
        flags = []
        if s.flag_unused: flags.append("⚠️ Unused?")
        if s.flag_duplicate_category: flags.append("⚠️ Duplicate?")
        rows.append({
            "Subscription": s.canonical_name,
            "Category": s.category.title(),
            "Cadence": s.cadence.title(),
            "Monthly ($)": f"{float(s.monthly_amount):,.2f}",
            "Annual ($)": f"{float(s.annual_amount):,.2f}",
            "Occurrences": s.occurrences,
            "First Seen": s.first_seen.strftime("%Y-%m-%d"),
            "Last Seen": s.last_seen.strftime("%Y-%m-%d"),
            "Flags": " Β· ".join(flags) if flags else "",
        })
    return pd.DataFrame(rows)


def audit_handler(csv_text: str):
    if not csv_text or not csv_text.strip():
        return (
            render_empty_state_cta(),
            None,
            None,
            generate_warning_image(),
            "",
        )

    try:
        txs = parse_bank_csv(csv_text)
    except Exception as e:
        return (
            f"### ❌ Couldn't parse CSV\n\n```\n{str(e)}\n```\n\nExpected columns: Date, Description, Amount.",
            None,
            None,
            generate_warning_image("CSV parse error"),
            "",
        )

    if not txs:
        return (
            "### ⚠️ No valid transactions found",
            None, None,
            generate_warning_image("No valid transactions"),
            "",
        )

    result = detect_subscriptions(txs)

    md = f"""## πŸ“Š Your Subscription Audit

| Metric | Value |
|---|---|
| **Active Subscriptions** | {result.total_subscriptions} |
| **Monthly Spend** | **${float(result.total_monthly_spend):,.2f}** |
| **Annual Spend** | **${float(result.total_annual_spend):,.2f}** |
| **Flagged Possibly Unused** | {len(result.flagged_unused)} |
| **Category Overlaps** | {len(result.flagged_duplicates)} |

"""

    if result.insights:
        md += "### πŸ’‘ Insights\n\n" + "\n".join(f"- {i}" for i in result.insights)

    df = _detected_to_dataframe(result.detected)

    # Top subscription for graphic
    top_name = ""
    top_amount = 0
    if result.detected:
        top = result.detected[0]
        top_name = top.canonical_name
        top_amount = float(top.monthly_amount)

    img_bytes = generate_summary_image(
        annual_spend=result.total_annual_spend,
        monthly_spend=result.total_monthly_spend,
        num_subscriptions=result.total_subscriptions,
        top_subscription_name=top_name,
        top_subscription_amount=top_amount,
        flagged_unused=len(result.flagged_unused),
    )
    img_path = tempfile.NamedTemporaryFile(mode='wb', suffix='_audit.png', delete=False)
    img_path.write(img_bytes)
    img_path.close()

    ctas = render_full_cta_stack(
        annual_spend=float(result.total_annual_spend),
        num_subs=result.total_subscriptions,
    )

    return md, df, None, img_path.name, ctas


EXAMPLE_CSV = """Date,Description,Amount
2026-01-15,NETFLIX.COM,15.49
2026-02-15,NETFLIX.COM,15.49
2026-03-15,NETFLIX.COM,15.49
2026-04-15,NETFLIX.COM,17.99
2026-01-22,Spotify USA,10.99
2026-02-22,Spotify USA,10.99
2026-03-22,Spotify USA,10.99
2026-01-03,ADOBE CREATIVE CLOUD,54.99
2026-02-03,ADOBE CREATIVE CLOUD,54.99
2026-03-03,ADOBE CREATIVE CLOUD,54.99
2025-09-15,Peloton Interactive,44.00
2025-10-15,Peloton Interactive,44.00
2025-11-15,Peloton Interactive,44.00
2026-01-10,CHATGPT PRO,20.00
2026-02-10,CHATGPT PRO,20.00
2026-03-10,CHATGPT PRO,20.00
2026-01-05,STARBUCKS #4521,8.45
2026-01-07,SHELL OIL,52.30
"""


with gr.Blocks(
    theme=gr.themes.Default(primary_hue="amber", secondary_hue="slate"),
    title="Subscription Audit β€” Free | LedgerLaunchCo",
    css="""
    .header-banner {
        background: #0F2D52;
        color: #D4A256;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
    }
    .header-banner h1 { margin: 0; font-weight: 800; }
    """,
) as demo:

    gr.HTML("""
    <div class="header-banner">
        <h1>πŸ“Š Free Subscription Audit</h1>
        <p>Find every recurring subscription in your bank statement. Most people discover $300-1500/year they didn't know they were spending. Private β€” your data stays in Hugging Face's compute and is not stored anywhere.</p>
    </div>
    """)

    with gr.Row():
        with gr.Column():
            gr.Markdown("### πŸ“₯ Paste your bank statement CSV")
            csv_input = gr.Textbox(
                label="CSV (Date, Description, Amount)",
                placeholder="Date,Description,Amount\n2026-01-15,NETFLIX.COM,15.49",
                lines=12,
                value=EXAMPLE_CSV,
                info="Compatible with most US bank exports (Chase, BofA, Wells Fargo, Capital One, Citi, Amex)",
            )
            run_btn = gr.Button("⚑ Run my audit", variant="primary", size="lg")

    gr.Markdown("---")

    with gr.Row():
        summary_md = gr.Markdown("*Run the audit to see your subscription report*")

    with gr.Row():
        share_img = gr.Image(label="πŸ“Έ Shareable summary (right-click to save)", type="filepath", height=540)

    with gr.Row():
        gr.Markdown("### πŸ“‹ Detected Subscriptions")
        detected_table = gr.Dataframe(label="All recurring charges detected")

    gr.Markdown("---")
    cta_block = gr.Markdown(render_empty_state_cta())

    run_btn.click(
        fn=audit_handler,
        inputs=[csv_input],
        outputs=[summary_md, detected_table, gr.State(), share_img, cta_block],
    )


if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)