Update app.py
Browse files
app.py
CHANGED
|
@@ -21,7 +21,7 @@ from supabase import create_client, Client
|
|
| 21 |
from groq import Groq
|
| 22 |
|
| 23 |
# ==========================================
|
| 24 |
-
# 1. KONFIGURACE A
|
| 25 |
# ==========================================
|
| 26 |
logging.basicConfig(level=logging.INFO)
|
| 27 |
logger = logging.getLogger(__name__)
|
|
@@ -36,12 +36,13 @@ STRIPE_PRICE_BASIC = os.getenv("STRIPE_PRICE_BASIC", "price_basic")
|
|
| 36 |
STRIPE_PRICE_PRO = os.getenv("STRIPE_PRICE_PRO", "price_pro")
|
| 37 |
STRIPE_PRICE_ENTERPRISE = os.getenv("STRIPE_PRICE_ENTERPRISE", "price_ent")
|
| 38 |
|
|
|
|
| 39 |
stripe.api_key = STRIPE_SECRET_KEY
|
| 40 |
-
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY) if SUPABASE_URL else None
|
| 41 |
groq_client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
|
| 42 |
|
| 43 |
# ==========================================
|
| 44 |
-
# 2. RATE LIMITING A
|
| 45 |
# ==========================================
|
| 46 |
class RateLimiter:
|
| 47 |
def __init__(self):
|
|
@@ -76,7 +77,7 @@ def validate_password_strength(password: str) -> bool:
|
|
| 76 |
return True
|
| 77 |
|
| 78 |
# ==========================================
|
| 79 |
-
# 3. AUTENTIZACE
|
| 80 |
# ==========================================
|
| 81 |
def hash_password(password: str) -> str:
|
| 82 |
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(rounds=12)).decode('utf-8')
|
|
@@ -101,11 +102,11 @@ def get_user_from_session(token: str):
|
|
| 101 |
return user_res.data[0] if user_res.data else None
|
| 102 |
|
| 103 |
# ==========================================
|
| 104 |
-
# 4. AI PIPELINE
|
| 105 |
# ==========================================
|
| 106 |
def ocr_tesseract(image: Image.Image) -> str:
|
| 107 |
try: return pytesseract.image_to_string(image, lang='eng')
|
| 108 |
-
except
|
| 109 |
|
| 110 |
def extract_with_groq(text: str) -> dict:
|
| 111 |
if not groq_client: return {}
|
|
@@ -156,12 +157,25 @@ def process_invoice_file(file_path: str, user_id: int) -> dict:
|
|
| 156 |
except Exception as e: return {"filename": os.path.basename(file_path), "status": "error", "error": str(e)}
|
| 157 |
|
| 158 |
# ==========================================
|
| 159 |
-
# 5. GRADIO
|
| 160 |
# ==========================================
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
-
ICON_BOLT = '<svg
|
| 164 |
-
ICON_UPLOAD = '<svg class="icon" viewBox="0 0 24 24"><path d="M9 16h6v-6h4l-7-7-7 7h4zm-4 2h14v2H5z"/></svg>'
|
| 165 |
|
| 166 |
def get_user_invoices(user_dict):
|
| 167 |
if not user_dict or not supabase: return pd.DataFrame()
|
|
@@ -169,7 +183,6 @@ def get_user_invoices(user_dict):
|
|
| 169 |
return pd.DataFrame(res.data)
|
| 170 |
|
| 171 |
def export_invoices_csv(user_dict):
|
| 172 |
-
"""Vygeneruje CSV soubor pro stažení."""
|
| 173 |
df = get_user_invoices(user_dict)
|
| 174 |
if df.empty: return None
|
| 175 |
temp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
|
|
@@ -177,7 +190,6 @@ def export_invoices_csv(user_dict):
|
|
| 177 |
return temp.name
|
| 178 |
|
| 179 |
def check_stripe_return(request: gr.Request):
|
| 180 |
-
"""Polling pro Stripe po návratu z checkoutu."""
|
| 181 |
if not request or 'checkout' not in request.query_params: return ""
|
| 182 |
if request.query_params.get('checkout') == 'success':
|
| 183 |
session_id = request.query_params.get('session_id')
|
|
@@ -195,6 +207,7 @@ def check_stripe_return(request: gr.Request):
|
|
| 195 |
def handle_login(email, password, request: gr.Request):
|
| 196 |
ip = request.client.host if request else "127.0.0.1"
|
| 197 |
if rate_limiter.is_rate_limited(f"login_{ip}", 5, 300): return None, "🚨 Příliš mnoho pokusů. Zkuste to za 5 minut."
|
|
|
|
| 198 |
res = supabase.table("users").select("*").eq("email", email).execute()
|
| 199 |
if not res.data: return None, "Neplatné přihlašovací údaje."
|
| 200 |
user = res.data[0]
|
|
@@ -206,6 +219,7 @@ def handle_signup(name, email, password, request: gr.Request):
|
|
| 206 |
if rate_limiter.is_rate_limited(f"signup_{ip}", 3, 3600): return None, "Příliš mnoho registrací z této IP."
|
| 207 |
if not validate_password_strength(password): return None, "Heslo musí mít min 12 znaků, 1 velké písmeno, 1 číslo a 1 speciální znak."
|
| 208 |
if check_password_leaked(password): return None, "Toto heslo bylo nalezen v databázi uniklých hesel."
|
|
|
|
| 209 |
exists = supabase.table("users").select("id").eq("email", email).execute()
|
| 210 |
if exists.data: return None, "E-mail je již registrován."
|
| 211 |
hashed = hash_password(password)
|
|
@@ -242,22 +256,18 @@ def create_stripe_checkout(plan: str, user_dict):
|
|
| 242 |
with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Default(primary_hue="emerald", neutral_hue="zinc")) as app:
|
| 243 |
user_state = gr.State(None)
|
| 244 |
stripe_status = gr.Markdown("", visible=False)
|
| 245 |
-
|
| 246 |
-
# Skrytý trigger pro Stripe callback
|
| 247 |
app.load(fn=check_stripe_return, outputs=stripe_status)
|
| 248 |
|
| 249 |
# VIEW 1: LANDING
|
| 250 |
with gr.Group(visible=True) as landing_view:
|
| 251 |
-
gr.
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
<
|
| 256 |
-
<
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
signup_trigger = gr.Button("Signup", elem_id="signup-trigger", visible=False)
|
| 260 |
-
|
| 261 |
# VIEW 2: AUTH
|
| 262 |
with gr.Group(visible=False) as auth_view:
|
| 263 |
with gr.Tabs():
|
|
@@ -272,17 +282,18 @@ with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Default(primary_hue="emerald", ne
|
|
| 272 |
signup_pass = gr.Textbox(label="Password (Min 12 chars, 1 upper, 1 number, 1 symbol)", type="password")
|
| 273 |
signup_btn = gr.Button("Create Account", variant="primary")
|
| 274 |
signup_msg = gr.Markdown()
|
| 275 |
-
back_btn = gr.Button("Back to Landing")
|
| 276 |
|
| 277 |
# VIEW 3: DASHBOARD
|
| 278 |
with gr.Group(visible=False) as dashboard_view:
|
| 279 |
-
gr.
|
|
|
|
|
|
|
| 280 |
with gr.Row():
|
| 281 |
with gr.Column(scale=1):
|
| 282 |
-
nav_upload = gr.Button(
|
| 283 |
-
nav_invoices = gr.Button("My Invoices")
|
| 284 |
-
nav_upgrade = gr.Button("Upgrade")
|
| 285 |
-
nav_logout = gr.Button("Log Out", variant="stop")
|
| 286 |
with gr.Column(scale=4):
|
| 287 |
with gr.Group(visible=True) as dash_upload:
|
| 288 |
upload_component = gr.File(file_count="multiple", file_types=[".pdf", ".png", ".jpg"])
|
|
@@ -295,14 +306,15 @@ with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Default(primary_hue="emerald", ne
|
|
| 295 |
csv_file = gr.File(label="Stáhnout CSV", visible=False)
|
| 296 |
|
| 297 |
with gr.Group(visible=False) as dash_upgrade:
|
| 298 |
-
gr.HTML("<h2>Upgrade Plan</h2>")
|
| 299 |
with gr.Row():
|
| 300 |
-
gr.HTML("<div class='card'><h3>Basic</h3><p>$29/mo</p></div>")
|
| 301 |
-
gr.HTML("<div class='card'><h3>Pro</h3><p>$129/mo</p></div>")
|
| 302 |
-
gr.HTML("<div class='card'><h3>Enterprise</h3><p>$499/mo</p></div>")
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
|
|
|
| 306 |
checkout_url = gr.Markdown()
|
| 307 |
|
| 308 |
# EVENT HANDLERY
|
|
@@ -323,9 +335,10 @@ with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Default(primary_hue="emerald", ne
|
|
| 323 |
signup_btn.click(fn=handle_signup, inputs=[signup_name, signup_email, signup_pass], outputs=[user_state, signup_msg])
|
| 324 |
|
| 325 |
def nav_switch(view_name):
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
elif view_name == "
|
|
|
|
| 329 |
|
| 330 |
nav_upload.click(fn=lambda: nav_switch("upload"), outputs=[dash_upload, dash_invoices, dash_upgrade])
|
| 331 |
nav_invoices.click(fn=lambda: nav_switch("invoices"), outputs=[dash_upload, dash_invoices, dash_upgrade])
|
|
@@ -342,8 +355,10 @@ with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Default(primary_hue="emerald", ne
|
|
| 342 |
upgrade_pro_btn.click(fn=lambda u: create_stripe_checkout("pro", u), inputs=[user_state], outputs=[checkout_url])
|
| 343 |
upgrade_ent_btn.click(fn=lambda u: create_stripe_checkout("enterprise", u), inputs=[user_state], outputs=[checkout_url])
|
| 344 |
|
| 345 |
-
|
| 346 |
-
|
|
|
|
|
|
|
| 347 |
|
| 348 |
if __name__ == "__main__":
|
| 349 |
app.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 21 |
from groq import Groq
|
| 22 |
|
| 23 |
# ==========================================
|
| 24 |
+
# 1. KONFIGURACE A BEZPEČNOST
|
| 25 |
# ==========================================
|
| 26 |
logging.basicConfig(level=logging.INFO)
|
| 27 |
logger = logging.getLogger(__name__)
|
|
|
|
| 36 |
STRIPE_PRICE_PRO = os.getenv("STRIPE_PRICE_PRO", "price_pro")
|
| 37 |
STRIPE_PRICE_ENTERPRISE = os.getenv("STRIPE_PRICE_ENTERPRISE", "price_ent")
|
| 38 |
|
| 39 |
+
# Bezpečná inicializace (degradace pokud chybí API klíče)
|
| 40 |
stripe.api_key = STRIPE_SECRET_KEY
|
| 41 |
+
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY) if SUPABASE_URL and SUPABASE_KEY else None
|
| 42 |
groq_client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
|
| 43 |
|
| 44 |
# ==========================================
|
| 45 |
+
# 2. RATE LIMITING A VALIDACE
|
| 46 |
# ==========================================
|
| 47 |
class RateLimiter:
|
| 48 |
def __init__(self):
|
|
|
|
| 77 |
return True
|
| 78 |
|
| 79 |
# ==========================================
|
| 80 |
+
# 3. AUTENTIZACE
|
| 81 |
# ==========================================
|
| 82 |
def hash_password(password: str) -> str:
|
| 83 |
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(rounds=12)).decode('utf-8')
|
|
|
|
| 102 |
return user_res.data[0] if user_res.data else None
|
| 103 |
|
| 104 |
# ==========================================
|
| 105 |
+
# 4. AI PIPELINE
|
| 106 |
# ==========================================
|
| 107 |
def ocr_tesseract(image: Image.Image) -> str:
|
| 108 |
try: return pytesseract.image_to_string(image, lang='eng')
|
| 109 |
+
except: return ""
|
| 110 |
|
| 111 |
def extract_with_groq(text: str) -> dict:
|
| 112 |
if not groq_client: return {}
|
|
|
|
| 157 |
except Exception as e: return {"filename": os.path.basename(file_path), "status": "error", "error": str(e)}
|
| 158 |
|
| 159 |
# ==========================================
|
| 160 |
+
# 5. GRADIO BACKEND FUNKCE
|
| 161 |
# ==========================================
|
| 162 |
+
CUSTOM_CSS = """
|
| 163 |
+
:root { --bg-primary: #09090b; --bg-secondary: #18181b; --bg-tertiary: #27272a; --border: #3f3f46; --text-primary: #f4f4f5; --text-secondary: #a1a1aa; --accent: #10b981; --accent-hover: #059669; --danger: #ef4444; }
|
| 164 |
+
* { box-sizing: border-box; font-family: 'Inter', sans-serif; }
|
| 165 |
+
body { background-color: var(--bg-primary) !important; color: var(--text-primary) !important; }
|
| 166 |
+
.gradio-container { max-width: 100% !important; padding: 0 !important; background: var(--bg-primary) !important; }
|
| 167 |
+
#header { padding: 20px 40px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; width: 100%; }
|
| 168 |
+
#hero { padding: 80px 40px; text-align: center; }
|
| 169 |
+
#hero h1 { font-size: 48px; margin-bottom: 16px; color: var(--text-primary); }
|
| 170 |
+
#hero p { font-size: 18px; color: var(--text-secondary); max-width: 600px; margin: 0 auto 32px auto; }
|
| 171 |
+
.main-btn { background: var(--accent) !important; color: white !important; border: none !important; padding: 12px 24px !important; border-radius: 6px !important; font-weight: 600 !important; cursor: pointer !important; transition: 0.2s !important; font-size: 16px !important; }
|
| 172 |
+
.main-btn:hover { background: var(--accent-hover) !important; }
|
| 173 |
+
.nav-btn { background: var(--bg-secondary) !important; color: var(--text-primary) !important; border: 1px solid var(--border) !important; text-align: left !important; margin-bottom: 8px !important; }
|
| 174 |
+
.card { background-color: var(--bg-secondary); border: 1px solid var(--border); border-radius: 8px; padding: 24px; margin-bottom: 16px; text-align: center; }
|
| 175 |
+
footer { display: none !important; }
|
| 176 |
+
"""
|
| 177 |
|
| 178 |
+
ICON_BOLT = '<svg style="width:24px;height:24px;display:inline-block;vertical-align:middle;margin-right:8px;" viewBox="0 0 24 24" fill="currentColor"><path d="M11 21h-1l1-7H7.5c-.58 0-.57-.32-.38-.66.19-.34.05-.08.07-.12C8.48 10.94 10.42 7.54 13 3h1l-1 7h3.5c.49 0 .56.33.47.51l-.07.15C12.96 17.55 11 21 11 21z"/></svg>'
|
|
|
|
| 179 |
|
| 180 |
def get_user_invoices(user_dict):
|
| 181 |
if not user_dict or not supabase: return pd.DataFrame()
|
|
|
|
| 183 |
return pd.DataFrame(res.data)
|
| 184 |
|
| 185 |
def export_invoices_csv(user_dict):
|
|
|
|
| 186 |
df = get_user_invoices(user_dict)
|
| 187 |
if df.empty: return None
|
| 188 |
temp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
|
|
|
|
| 190 |
return temp.name
|
| 191 |
|
| 192 |
def check_stripe_return(request: gr.Request):
|
|
|
|
| 193 |
if not request or 'checkout' not in request.query_params: return ""
|
| 194 |
if request.query_params.get('checkout') == 'success':
|
| 195 |
session_id = request.query_params.get('session_id')
|
|
|
|
| 207 |
def handle_login(email, password, request: gr.Request):
|
| 208 |
ip = request.client.host if request else "127.0.0.1"
|
| 209 |
if rate_limiter.is_rate_limited(f"login_{ip}", 5, 300): return None, "🚨 Příliš mnoho pokusů. Zkuste to za 5 minut."
|
| 210 |
+
if not supabase: return None, "DB Error"
|
| 211 |
res = supabase.table("users").select("*").eq("email", email).execute()
|
| 212 |
if not res.data: return None, "Neplatné přihlašovací údaje."
|
| 213 |
user = res.data[0]
|
|
|
|
| 219 |
if rate_limiter.is_rate_limited(f"signup_{ip}", 3, 3600): return None, "Příliš mnoho registrací z této IP."
|
| 220 |
if not validate_password_strength(password): return None, "Heslo musí mít min 12 znaků, 1 velké písmeno, 1 číslo a 1 speciální znak."
|
| 221 |
if check_password_leaked(password): return None, "Toto heslo bylo nalezen v databázi uniklých hesel."
|
| 222 |
+
if not supabase: return None, "DB Error"
|
| 223 |
exists = supabase.table("users").select("id").eq("email", email).execute()
|
| 224 |
if exists.data: return None, "E-mail je již registrován."
|
| 225 |
hashed = hash_password(password)
|
|
|
|
| 256 |
with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Default(primary_hue="emerald", neutral_hue="zinc")) as app:
|
| 257 |
user_state = gr.State(None)
|
| 258 |
stripe_status = gr.Markdown("", visible=False)
|
|
|
|
|
|
|
| 259 |
app.load(fn=check_stripe_return, outputs=stripe_status)
|
| 260 |
|
| 261 |
# VIEW 1: LANDING
|
| 262 |
with gr.Group(visible=True) as landing_view:
|
| 263 |
+
with gr.Row(elem_id="header"):
|
| 264 |
+
gr.HTML(f"<div style='font-weight:bold;font-size:20px;'>{ICON_BOLT} OmniParse AI</div>")
|
| 265 |
+
auth_trigger = gr.Button("Log In", elem_classes="main-btn", size="sm")
|
| 266 |
+
with gr.Column(elem_id="hero"):
|
| 267 |
+
gr.HTML("<h1>Invoice processing in <span style='color: #10b981;'>seconds</span>, not hours.</h1>")
|
| 268 |
+
gr.HTML("<p>AI extracts vendor, dates, amounts and line items from any PDF or image. Export to CSV, JSON or Excel. Connect via API.</p>")
|
| 269 |
+
signup_trigger = gr.Button("Start Free — 20 invoices", elem_classes="main-btn", size="lg")
|
| 270 |
+
|
|
|
|
|
|
|
| 271 |
# VIEW 2: AUTH
|
| 272 |
with gr.Group(visible=False) as auth_view:
|
| 273 |
with gr.Tabs():
|
|
|
|
| 282 |
signup_pass = gr.Textbox(label="Password (Min 12 chars, 1 upper, 1 number, 1 symbol)", type="password")
|
| 283 |
signup_btn = gr.Button("Create Account", variant="primary")
|
| 284 |
signup_msg = gr.Markdown()
|
| 285 |
+
back_btn = gr.Button("Back to Landing", variant="stop")
|
| 286 |
|
| 287 |
# VIEW 3: DASHBOARD
|
| 288 |
with gr.Group(visible=False) as dashboard_view:
|
| 289 |
+
with gr.Row(elem_id="header"):
|
| 290 |
+
gr.HTML(f"<div style='font-weight:bold;font-size:20px;'>{ICON_BOLT} Dashboard</div>")
|
| 291 |
+
nav_logout = gr.Button("Log Out", variant="stop", size="sm")
|
| 292 |
with gr.Row():
|
| 293 |
with gr.Column(scale=1):
|
| 294 |
+
nav_upload = gr.Button("Upload", elem_classes="nav-btn")
|
| 295 |
+
nav_invoices = gr.Button("My Invoices", elem_classes="nav-btn")
|
| 296 |
+
nav_upgrade = gr.Button("Upgrade", elem_classes="nav-btn")
|
|
|
|
| 297 |
with gr.Column(scale=4):
|
| 298 |
with gr.Group(visible=True) as dash_upload:
|
| 299 |
upload_component = gr.File(file_count="multiple", file_types=[".pdf", ".png", ".jpg"])
|
|
|
|
| 306 |
csv_file = gr.File(label="Stáhnout CSV", visible=False)
|
| 307 |
|
| 308 |
with gr.Group(visible=False) as dash_upgrade:
|
| 309 |
+
gr.HTML("<h2 style='text-align:center;'>Upgrade Plan</h2>")
|
| 310 |
with gr.Row():
|
| 311 |
+
gr.HTML("<div class='card'><h3>Basic</h3><p style='font-size:24px;color:#10b981;'>$29/mo</p></div>")
|
| 312 |
+
gr.HTML("<div class='card'><h3>Pro</h3><p style='font-size:24px;color:#10b981;'>$129/mo</p></div>")
|
| 313 |
+
gr.HTML("<div class='card'><h3>Enterprise</h3><p style='font-size:24px;color:#10b981;'>$499/mo</p></div>")
|
| 314 |
+
with gr.Row():
|
| 315 |
+
upgrade_basic_btn = gr.Button("Upgrade to Basic")
|
| 316 |
+
upgrade_pro_btn = gr.Button("Upgrade to Pro")
|
| 317 |
+
upgrade_ent_btn = gr.Button("Upgrade to Enterprise")
|
| 318 |
checkout_url = gr.Markdown()
|
| 319 |
|
| 320 |
# EVENT HANDLERY
|
|
|
|
| 335 |
signup_btn.click(fn=handle_signup, inputs=[signup_name, signup_email, signup_pass], outputs=[user_state, signup_msg])
|
| 336 |
|
| 337 |
def nav_switch(view_name):
|
| 338 |
+
u = gr.update(visible=False)
|
| 339 |
+
if view_name == "upload": return gr.update(visible=True), u, u
|
| 340 |
+
elif view_name == "invoices": return u, gr.update(visible=True), u
|
| 341 |
+
elif view_name == "upgrade": return u, u, gr.update(visible=True)
|
| 342 |
|
| 343 |
nav_upload.click(fn=lambda: nav_switch("upload"), outputs=[dash_upload, dash_invoices, dash_upgrade])
|
| 344 |
nav_invoices.click(fn=lambda: nav_switch("invoices"), outputs=[dash_upload, dash_invoices, dash_upgrade])
|
|
|
|
| 355 |
upgrade_pro_btn.click(fn=lambda u: create_stripe_checkout("pro", u), inputs=[user_state], outputs=[checkout_url])
|
| 356 |
upgrade_ent_btn.click(fn=lambda u: create_stripe_checkout("enterprise", u), inputs=[user_state], outputs=[checkout_url])
|
| 357 |
|
| 358 |
+
def logout():
|
| 359 |
+
return None, gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
|
| 360 |
+
|
| 361 |
+
nav_logout.click(fn=logout, outputs=[user_state, landing_view, auth_view, dashboard_view])
|
| 362 |
|
| 363 |
if __name__ == "__main__":
|
| 364 |
app.launch(server_name="0.0.0.0", server_port=7860)
|