Update app.py
Browse files
app.py
CHANGED
|
@@ -29,32 +29,23 @@ logger = logging.getLogger(__name__)
|
|
| 29 |
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
| 30 |
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
|
| 31 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 32 |
-
GOOGLE_VISION_KEY = os.getenv("GOOGLE_VISION_KEY")
|
| 33 |
STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY")
|
| 34 |
APP_URL = os.getenv("APP_URL", "http://localhost:7860")
|
| 35 |
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 |
-
# 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):
|
| 49 |
-
self.requests = {}
|
| 50 |
-
|
| 51 |
def is_rate_limited(self, key: str, limit: int, period: int) -> bool:
|
| 52 |
now = time.time()
|
| 53 |
-
if key not in self.requests:
|
| 54 |
-
self.requests[key] = []
|
| 55 |
self.requests[key] = [t for t in self.requests[key] if now - t < period]
|
| 56 |
-
if len(self.requests[key]) >= limit:
|
| 57 |
-
return True
|
| 58 |
self.requests[key].append(now)
|
| 59 |
return False
|
| 60 |
|
|
@@ -76,33 +67,14 @@ def validate_password_strength(password: str) -> bool:
|
|
| 76 |
if not re.search(r"[!@#$%^&*(),.?\":{}|<>]", password): return False
|
| 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')
|
| 84 |
|
| 85 |
def verify_password(password: str, hashed: str) -> bool:
|
| 86 |
return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))
|
| 87 |
|
| 88 |
-
def create_session(user_id: int) -> str:
|
| 89 |
-
token = secrets.token_urlsafe(32)
|
| 90 |
-
expires_at = (datetime.utcnow() + timedelta(days=7)).isoformat()
|
| 91 |
-
if supabase:
|
| 92 |
-
supabase.table("sessions").insert({"token": token, "user_id": user_id, "expires_at": expires_at}).execute()
|
| 93 |
-
return token
|
| 94 |
-
|
| 95 |
-
def get_user_from_session(token: str):
|
| 96 |
-
if not token or not supabase: return None
|
| 97 |
-
res = supabase.table("sessions").select("user_id, expires_at").eq("token", token).execute()
|
| 98 |
-
if not res.data: return None
|
| 99 |
-
expires_at = datetime.fromisoformat(res.data[0]["expires_at"])
|
| 100 |
-
if datetime.utcnow() > expires_at: return None
|
| 101 |
-
user_res = supabase.table("users").select("*").eq("id", res.data[0]["user_id"]).execute()
|
| 102 |
-
return user_res.data[0] if user_res.data else None
|
| 103 |
-
|
| 104 |
# ==========================================
|
| 105 |
-
#
|
| 106 |
# ==========================================
|
| 107 |
def ocr_tesseract(image: Image.Image) -> str:
|
| 108 |
try: return pytesseract.image_to_string(image, lang='eng')
|
|
@@ -110,26 +82,14 @@ def ocr_tesseract(image: Image.Image) -> str:
|
|
| 110 |
|
| 111 |
def extract_with_groq(text: str) -> dict:
|
| 112 |
if not groq_client: return {}
|
| 113 |
-
prompt = f"Extract invoice data
|
| 114 |
try:
|
| 115 |
chat_completion = groq_client.chat.completions.create(
|
| 116 |
-
messages=[{"role": "user", "content": prompt}],
|
| 117 |
-
model="llama-3.1-8b-instant", max_tokens=512, temperature=0.05
|
| 118 |
)
|
| 119 |
-
|
| 120 |
-
return json.loads(content.strip().strip('```json'))
|
| 121 |
except: return {}
|
| 122 |
|
| 123 |
-
def regex_fallback(text: str) -> dict:
|
| 124 |
-
data = {}
|
| 125 |
-
inv_match = re.search(r'(?:invoice|inv)[#:\s]+([A-Z0-9-]{4,24})', text, re.I)
|
| 126 |
-
if inv_match: data['inv_number'] = inv_match.group(1)
|
| 127 |
-
total_match = re.search(r'(?:total|amount due)[\s:$]+([0-9,\.]+)', text, re.I)
|
| 128 |
-
if total_match: data['total'] = float(total_match.group(1).replace(',', ''))
|
| 129 |
-
lines = [l.strip() for l in text.split('\n') if l.strip()]
|
| 130 |
-
if lines: data['vendor'] = lines[0]
|
| 131 |
-
return data
|
| 132 |
-
|
| 133 |
def process_invoice_file(file_path: str, user_id: int) -> dict:
|
| 134 |
try:
|
| 135 |
with open(file_path, 'rb') as f: file_bytes = f.read()
|
|
@@ -140,225 +100,197 @@ def process_invoice_file(file_path: str, user_id: int) -> dict:
|
|
| 140 |
full_text = ""
|
| 141 |
for img in images: full_text += ocr_tesseract(img) + "\n"
|
| 142 |
|
| 143 |
-
|
| 144 |
-
if not
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
if supabase:
|
| 150 |
-
supabase.table("invoices").insert({
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
"total": extracted_data.get('total'), "currency": extracted_data.get('currency', 'USD'),
|
| 154 |
-
"status": "done", "raw_json": extracted_data
|
| 155 |
-
}).execute()
|
| 156 |
-
return extracted_data
|
| 157 |
-
except Exception as e: return {"filename": os.path.basename(file_path), "status": "error", "error": str(e)}
|
| 158 |
|
| 159 |
# ==========================================
|
| 160 |
-
#
|
| 161 |
# ==========================================
|
| 162 |
CUSTOM_CSS = """
|
| 163 |
-
|
|
|
|
|
|
|
| 164 |
* { box-sizing: border-box; font-family: 'Inter', sans-serif; }
|
| 165 |
-
body { background
|
| 166 |
-
.gradio-container { max-width: 100% !important; padding: 0 !important; background: var(--bg
|
| 167 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
df.to_csv(temp.name, index=False)
|
| 190 |
-
return temp.name
|
| 191 |
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
session_id = request.query_params.get('session_id')
|
| 196 |
-
if session_id and STRIPE_SECRET_KEY:
|
| 197 |
-
try:
|
| 198 |
-
session = stripe.checkout.Session.retrieve(session_id)
|
| 199 |
-
if session.payment_status == "paid" and supabase:
|
| 200 |
-
supabase.table("users").update({
|
| 201 |
-
"plan": session.metadata["plan"], "stripe_cid": session.customer
|
| 202 |
-
}).eq("id", session.metadata["user_id"]).execute()
|
| 203 |
-
return "✅ Platba úspěšná! Váš plán byl upgradován."
|
| 204 |
-
except: return "⏳ Zpracováváme platbu..."
|
| 205 |
-
return ""
|
| 206 |
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 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]
|
| 214 |
-
if not verify_password(password, user['password']): return None, "Neplatné přihlašovací údaje."
|
| 215 |
-
return user, "Přihlášení úspěšné!"
|
| 216 |
|
| 217 |
-
|
| 218 |
-
ip = request.client.host if request else "127.0.0.1"
|
| 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)
|
| 226 |
-
supabase.table("users").insert({
|
| 227 |
-
"name": name, "email": email, "password": hashed, "plan": "free", "is_verified": True, "api_key": f"op_live_{secrets.token_urlsafe(24)}"
|
| 228 |
-
}).execute()
|
| 229 |
-
return None, "Registrace OK. Můžete se přihlásit."
|
| 230 |
|
| 231 |
-
def
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
-
def
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
# ==========================================
|
| 254 |
-
#
|
| 255 |
# ==========================================
|
| 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 |
-
|
| 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():
|
| 274 |
-
with gr.Tab("Log In"):
|
| 275 |
-
login_email = gr.Textbox(label="Email")
|
| 276 |
-
login_pass = gr.Textbox(label="Password", type="password")
|
| 277 |
-
login_btn = gr.Button("Log In", variant="primary")
|
| 278 |
-
login_msg = gr.Markdown()
|
| 279 |
-
with gr.Tab("Sign Up"):
|
| 280 |
-
signup_name = gr.Textbox(label="Full Name")
|
| 281 |
-
signup_email = gr.Textbox(label="Work Email")
|
| 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"])
|
| 300 |
-
process_btn = gr.Button("Process Invoices", variant="primary")
|
| 301 |
-
upload_status = gr.Markdown()
|
| 302 |
-
|
| 303 |
-
with gr.Group(visible=False) as dash_invoices:
|
| 304 |
-
invoices_table = gr.Dataframe(headers=["ID", "Vendor", "Invoice#", "Total", "Status"], wrap=True)
|
| 305 |
-
export_btn = gr.Button("Export to CSV")
|
| 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
|
| 321 |
-
def show_auth(): return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
|
| 322 |
-
def show_landing(): return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
|
| 323 |
-
def show_dashboard(user):
|
| 324 |
-
if not user: return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
|
| 325 |
-
return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
|
| 326 |
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
|
|
|
|
|
|
| 330 |
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
if
|
| 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 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
return
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
|
| 363 |
if __name__ == "__main__":
|
| 364 |
app.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 29 |
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
| 30 |
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
|
| 31 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
|
|
|
| 32 |
STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY")
|
| 33 |
APP_URL = os.getenv("APP_URL", "http://localhost:7860")
|
| 34 |
STRIPE_PRICE_BASIC = os.getenv("STRIPE_PRICE_BASIC", "price_basic")
|
| 35 |
STRIPE_PRICE_PRO = os.getenv("STRIPE_PRICE_PRO", "price_pro")
|
| 36 |
STRIPE_PRICE_ENTERPRISE = os.getenv("STRIPE_PRICE_ENTERPRISE", "price_ent")
|
| 37 |
|
|
|
|
| 38 |
stripe.api_key = STRIPE_SECRET_KEY
|
| 39 |
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY) if SUPABASE_URL and SUPABASE_KEY else None
|
| 40 |
groq_client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
|
| 41 |
|
|
|
|
|
|
|
|
|
|
| 42 |
class RateLimiter:
|
| 43 |
+
def __init__(self): self.requests = {}
|
|
|
|
|
|
|
| 44 |
def is_rate_limited(self, key: str, limit: int, period: int) -> bool:
|
| 45 |
now = time.time()
|
| 46 |
+
if key not in self.requests: self.requests[key] = []
|
|
|
|
| 47 |
self.requests[key] = [t for t in self.requests[key] if now - t < period]
|
| 48 |
+
if len(self.requests[key]) >= limit: return True
|
|
|
|
| 49 |
self.requests[key].append(now)
|
| 50 |
return False
|
| 51 |
|
|
|
|
| 67 |
if not re.search(r"[!@#$%^&*(),.?\":{}|<>]", password): return False
|
| 68 |
return True
|
| 69 |
|
|
|
|
|
|
|
|
|
|
| 70 |
def hash_password(password: str) -> str:
|
| 71 |
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(rounds=12)).decode('utf-8')
|
| 72 |
|
| 73 |
def verify_password(password: str, hashed: str) -> bool:
|
| 74 |
return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))
|
| 75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
# ==========================================
|
| 77 |
+
# 2. AI PIPELINE
|
| 78 |
# ==========================================
|
| 79 |
def ocr_tesseract(image: Image.Image) -> str:
|
| 80 |
try: return pytesseract.image_to_string(image, lang='eng')
|
|
|
|
| 82 |
|
| 83 |
def extract_with_groq(text: str) -> dict:
|
| 84 |
if not groq_client: return {}
|
| 85 |
+
prompt = f"Extract invoice data. Return ONLY JSON. Keys: vendor, inv_number, inv_date, due_date, amount, vat_amount, total, currency. Text: {text[:3000]}"
|
| 86 |
try:
|
| 87 |
chat_completion = groq_client.chat.completions.create(
|
| 88 |
+
messages=[{"role": "user", "content": prompt}], model="llama-3.1-8b-instant", max_tokens=512, temperature=0.05
|
|
|
|
| 89 |
)
|
| 90 |
+
return json.loads(chat_completion.choices[0].message.content.strip().strip('```json'))
|
|
|
|
| 91 |
except: return {}
|
| 92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
def process_invoice_file(file_path: str, user_id: int) -> dict:
|
| 94 |
try:
|
| 95 |
with open(file_path, 'rb') as f: file_bytes = f.read()
|
|
|
|
| 100 |
full_text = ""
|
| 101 |
for img in images: full_text += ocr_tesseract(img) + "\n"
|
| 102 |
|
| 103 |
+
data = extract_with_groq(full_text)
|
| 104 |
+
if not data:
|
| 105 |
+
inv_match = re.search(r'(?:invoice|inv)[#:\s]+([A-Z0-9-]{4,24})', full_text, re.I)
|
| 106 |
+
if inv_match: data['inv_number'] = inv_match.group(1)
|
| 107 |
+
total_match = re.search(r'(?:total|amount due)[\s:$]+([0-9,\.]+)', full_text, re.I)
|
| 108 |
+
if total_match: data['total'] = float(total_match.group(1).replace(',', ''))
|
| 109 |
+
lines = [l.strip() for l in full_text.split('\n') if l.strip()]
|
| 110 |
+
if lines: data['vendor'] = lines[0]
|
| 111 |
+
|
| 112 |
+
data['filename'] = os.path.basename(file_path)
|
| 113 |
if supabase:
|
| 114 |
+
supabase.table("invoices").insert({"user_id": user_id, "filename": data.get('filename'), "vendor": data.get('vendor'), "inv_number": data.get('inv_number'), "total": data.get('total'), "status": "done"}).execute()
|
| 115 |
+
return data
|
| 116 |
+
except Exception as e: return {"filename": os.path.basename(file_path), "status": "error"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
# ==========================================
|
| 119 |
+
# 3. UI HTML TEMPLATES (Design System)
|
| 120 |
# ==========================================
|
| 121 |
CUSTOM_CSS = """
|
| 122 |
+
/* Obsidian Glassmorphism Theme */
|
| 123 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
|
| 124 |
+
:root { --bg: #09090b; --card: rgba(255,255,255,0.03); --border: rgba(255,255,255,0.08); --text: #f4f4f5; --muted: #71717a; --accent: #10b981; --accent-glow: rgba(16,185,129,0.2); }
|
| 125 |
* { box-sizing: border-box; font-family: 'Inter', sans-serif; }
|
| 126 |
+
body { background: var(--bg); color: var(--text); margin: 0; overflow-x: hidden; }
|
| 127 |
+
.gradio-container { max-width: 100% !important; padding: 0 !important; background: var(--bg) !important; min-height: 100vh; }
|
| 128 |
+
.hide { display: none !important; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
+
/* Custom Layouts */
|
| 131 |
+
.app-container { padding: 40px; max-width: 1200px; margin: 0 auto; }
|
| 132 |
+
.navbar { display: flex; justify-content: space-between; align-items: center; padding: 20px 40px; border-bottom: 1px solid var(--border); backdrop-filter: blur(10px); position: sticky; top: 0; background: rgba(9,9,11,0.8); z-index: 100; }
|
| 133 |
+
.logo { font-weight: 700; font-size: 20px; display: flex; align-items: center; gap: 10px; }
|
| 134 |
+
.logo svg { width: 24px; height: 24px; fill: var(--accent); }
|
| 135 |
|
| 136 |
+
/* Components */
|
| 137 |
+
.btn { background: var(--accent); color: #000; border: none; padding: 12px 24px; border-radius: 8px; font-weight: 600; cursor: pointer; transition: 0.2s; text-decoration: none; display: inline-block; }
|
| 138 |
+
.btn:hover { box-shadow: 0 0 20px var(--accent-glow); transform: translateY(-1px); }
|
| 139 |
+
.btn-ghost { background: transparent; border: 1px solid var(--border); color: var(--text); }
|
| 140 |
+
.btn-ghost:hover { border-color: var(--accent); color: var(--accent); }
|
| 141 |
+
.card { background: var(--card); border: 1px solid var(--border); border-radius: 16px; padding: 24px; backdrop-filter: blur(20px); margin-bottom: 20px; }
|
| 142 |
+
.input { background: rgba(0,0,0,0.3) !important; border: 1px solid var(--border) !important; border-radius: 8px !important; padding: 12px !important; color: var(--text) !important; width: 100% !important; margin-bottom: 16px !important; }
|
| 143 |
+
.input:focus { border-color: var(--accent) !important; outline: none !important; }
|
| 144 |
|
| 145 |
+
/* Hero */
|
| 146 |
+
.hero { text-align: center; padding: 100px 20px; }
|
| 147 |
+
.hero h1 { font-size: 56px; font-weight: 700; margin-bottom: 24px; background: linear-gradient(180deg, #fff 0%, #a1a1aa 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; line-height: 1.1; }
|
| 148 |
+
.hero p { font-size: 20px; color: var(--muted); max-width: 600px; margin: 0 auto 40px; }
|
|
|
|
|
|
|
| 149 |
|
| 150 |
+
/* Skeleton Loader */
|
| 151 |
+
.skeleton { background: linear-gradient(90deg, rgba(255,255,255,0.05) 25%, rgba(255,255,255,0.1) 50%, rgba(255,255,255,0.05) 75%); background-size: 200% 100%; animation: skeleton 1.5s infinite; border-radius: 4px; height: 20px; margin-bottom: 10px; }
|
| 152 |
+
@keyframes skeleton { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
+
/* Gradio Overrides */
|
| 155 |
+
.gradio-container .form { background: transparent !important; border: none !important; }
|
| 156 |
+
footer { display: none !important; }
|
| 157 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
+
ICON_BOLT = '<svg viewBox="0 0 24 24"><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>'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
+
def render_landing():
|
| 162 |
+
return f"""
|
| 163 |
+
<div class="navbar">
|
| 164 |
+
<div class="logo">{ICON_BOLT} OmniParse AI</div>
|
| 165 |
+
<div style="display:flex; gap:12px;">
|
| 166 |
+
<button class="btn btn-ghost" id="nav-auth">Log In</button>
|
| 167 |
+
<button class="btn" id="nav-signup">Start Free</button>
|
| 168 |
+
</div>
|
| 169 |
+
</div>
|
| 170 |
+
<div class="hero">
|
| 171 |
+
<h1>Invoice processing in <span style="color: var(--accent);">seconds</span>, not hours.</h1>
|
| 172 |
+
<p>AI extracts vendor, dates, amounts and line items from any PDF or image. Export to CSV, JSON or Excel. Connect via API.</p>
|
| 173 |
+
<button class="btn" style="font-size: 18px; padding: 16px 32px;" id="hero-cta">Start Free — 20 invoices</button>
|
| 174 |
+
<div style="margin-top: 40px; color: var(--muted); font-size: 14px;">
|
| 175 |
+
99.2% accuracy · <4s per invoice · 40+ formats supported
|
| 176 |
+
</div>
|
| 177 |
+
</div>
|
| 178 |
+
<div class="app-container">
|
| 179 |
+
<div class="card" style="display:grid; grid-template-columns:1fr 1fr 1fr; gap:20px;">
|
| 180 |
+
<div><h3 style="color:var(--accent);">1. Upload</h3><p style="color:var(--muted)">Drag & drop PDF or Image</p></div>
|
| 181 |
+
<div><h3 style="color:var(--accent);">2. AI Extract</h3><p style="color:var(--muted)">Groq + Tesseract OCR</p></div>
|
| 182 |
+
<div><h3 style="color:var(--accent);">3. Export</h3><p style="color:var(--muted)">CSV, JSON, Excel</p></div>
|
| 183 |
+
</div>
|
| 184 |
+
</div>
|
| 185 |
+
"""
|
| 186 |
|
| 187 |
+
def render_auth():
|
| 188 |
+
return """
|
| 189 |
+
<div class="app-container" style="max-width: 450px; margin-top: 80px;">
|
| 190 |
+
<div class="card">
|
| 191 |
+
<h2 style="text-align:center; margin-bottom: 24px;">Welcome to OmniParse</h2>
|
| 192 |
+
<input type="text" class="input" id="auth-email" placeholder="Work Email">
|
| 193 |
+
<input type="password" class="input" id="auth-pass" placeholder="Password (Min 12 chars)">
|
| 194 |
+
<button class="btn" style="width:100%;" id="auth-submit">Log In / Sign Up</button>
|
| 195 |
+
<p style="text-align:center; color:var(--muted); margin-top:16px; font-size:14px;" id="auth-msg"></p>
|
| 196 |
+
<button class="btn btn-ghost" style="width:100%; margin-top:16px;" id="auth-back">Back to Home</button>
|
| 197 |
+
</div>
|
| 198 |
+
</div>
|
| 199 |
+
"""
|
| 200 |
+
|
| 201 |
+
def render_dashboard(user, table_html, status_msg=""):
|
| 202 |
+
plan = user.get('plan', 'free').upper() if user else 'FREE'
|
| 203 |
+
msg_html = f"<div style='color:var(--accent); margin-bottom:20px;'>{status_msg}</div>" if status_msg else ""
|
| 204 |
+
|
| 205 |
+
return f"""
|
| 206 |
+
<div class="navbar">
|
| 207 |
+
<div class="logo">{ICON_BOLT} OmniParse AI</div>
|
| 208 |
+
<div style="display:flex; gap:12px; align-items:center;">
|
| 209 |
+
<span style="color:var(--muted); font-size:14px;">Plan: <strong style="color:var(--accent);">{plan}</strong></span>
|
| 210 |
+
<button class="btn btn-ghost" id="dash-logout">Log Out</button>
|
| 211 |
+
</div>
|
| 212 |
+
</div>
|
| 213 |
+
<div class="app-container" style="display:grid; grid-template-columns: 250px 1fr; gap: 30px;">
|
| 214 |
+
<div class="card" style="padding: 16px;">
|
| 215 |
+
<button class="btn btn-ghost" style="width:100%; margin-bottom:10px; text-align:left;" id="nav-upload">Upload Invoice</button>
|
| 216 |
+
<button class="btn btn-ghost" style="width:100%; margin-bottom:10px; text-align:left;" id="nav-invoices">My Invoices</button>
|
| 217 |
+
<button class="btn btn-ghost" style="width:100%; text-align:left;" id="nav-upgrade">Upgrade</button>
|
| 218 |
+
</div>
|
| 219 |
+
<div id="dash-content">
|
| 220 |
+
{msg_html}
|
| 221 |
+
{table_html}
|
| 222 |
+
</div>
|
| 223 |
+
</div>
|
| 224 |
+
"""
|
| 225 |
|
| 226 |
# ==========================================
|
| 227 |
+
# 4. GRADIO APP (Invisible Bridge)
|
| 228 |
# ==========================================
|
| 229 |
with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Default(primary_hue="emerald", neutral_hue="zinc")) as app:
|
| 230 |
user_state = gr.State(None)
|
| 231 |
+
ui_container = gr.HTML(render_landing())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
+
# Neviditelné Gradio komponenty pro backend komunikaci
|
| 234 |
+
hidden_action = gr.Textbox(elem_id="hidden-action", visible=False)
|
| 235 |
+
hidden_email = gr.Textbox(elem_id="hidden-email", visible=False)
|
| 236 |
+
hidden_pass = gr.Textbox(elem_id="hidden-pass", visible=False)
|
| 237 |
+
hidden_files = gr.File(elem_id="hidden-files", visible=False, file_count="multiple")
|
| 238 |
|
| 239 |
+
# JavaScript inject pro přepínanie view a sběr dat
|
| 240 |
+
gr.HTML("""
|
| 241 |
+
<script>
|
| 242 |
+
function triggerAction(action, data={}) {
|
| 243 |
+
document.getElementById('hidden-action').value = action;
|
| 244 |
+
document.getElementById('hidden-action').dispatchEvent(new Event('input'));
|
| 245 |
+
if(data.email) document.getElementById('hidden-email').value = data.email;
|
| 246 |
+
if(data.pass) document.getElementById('hidden-pass').value = data.pass;
|
| 247 |
+
}
|
| 248 |
|
| 249 |
+
document.addEventListener('click', function(e) {
|
| 250 |
+
if(e.target.id === 'nav-auth' || e.target.id === 'nav-signup' || e.target.id === 'hero-cta') triggerAction('show_auth');
|
| 251 |
+
if(e.target.id === 'auth-back') triggerAction('show_landing');
|
| 252 |
+
if(e.target.id === 'auth-submit') triggerAction('auth', {email: document.getElementById('auth-email').value, pass: document.getElementById('auth-pass').value});
|
| 253 |
+
if(e.target.id === 'dash-logout') triggerAction('logout');
|
|
|
|
|
|
|
| 254 |
|
| 255 |
+
if(e.target.id === 'nav-upload') document.getElementById('hidden-files').click();
|
| 256 |
+
if(e.target.id === 'nav-invoices') triggerAction('show_invoices');
|
| 257 |
+
if(e.target.id === 'nav-upgrade') triggerAction('show_upgrade');
|
| 258 |
+
});
|
| 259 |
+
</script>
|
| 260 |
+
""")
|
| 261 |
+
|
| 262 |
+
def router(action, email, pass_val, files, user):
|
| 263 |
+
if not action: return render_landing(), user
|
| 264 |
+
|
| 265 |
+
if action == "show_auth":
|
| 266 |
+
return render_auth(), user
|
| 267 |
+
|
| 268 |
+
elif action == "show_landing":
|
| 269 |
+
return render_landing(), user
|
| 270 |
+
|
| 271 |
+
elif action == "auth":
|
| 272 |
+
if not supabase: return render_auth().replace('<p id="auth-msg"></p>', '<p id="auth-msg" style="color:var(--accent);">DB Error</p>'), user
|
| 273 |
+
# Try Login
|
| 274 |
+
res = supabase.table("users").select("*").eq("email", email).execute()
|
| 275 |
+
if res.data and verify_password(pass_val, res.data[0]['password']):
|
| 276 |
+
user = res.data[0]
|
| 277 |
+
return render_dashboard(user, "<div class='card'>Welcome back!</div>"), user
|
| 278 |
+
# Try Signup
|
| 279 |
+
if not res.data:
|
| 280 |
+
if not validate_password_strength(pass_val):
|
| 281 |
+
return render_auth().replace('<p id="auth-msg"></p>', '<p id="auth-msg" style="color:#ef4444;">Weak password.</p>'), user
|
| 282 |
+
hashed = hash_password(pass_val)
|
| 283 |
+
new_user = supabase.table("users").insert({"email": email, "password": hashed, "plan": "free"}).execute()
|
| 284 |
+
user = new_user.data[0]
|
| 285 |
+
return render_dashboard(user, "<div class='card'>Account created!</div>"), user
|
| 286 |
+
return render_auth().replace('<p id="auth-msg"></p>', '<p id="auth-msg" style="color:#ef4444;">Invalid credentials.</p>'), user
|
| 287 |
+
|
| 288 |
+
elif action == "logout":
|
| 289 |
+
return render_landing(), None
|
| 290 |
+
|
| 291 |
+
return render_landing(), user
|
| 292 |
+
|
| 293 |
+
hidden_action.change(fn=router, inputs=[hidden_action, hidden_email, hidden_pass, hidden_files, user_state], outputs=[ui_container, user_state])
|
| 294 |
|
| 295 |
if __name__ == "__main__":
|
| 296 |
app.launch(server_name="0.0.0.0", server_port=7860)
|