forked from farazshoukat/ai-invoice-extractor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsheets.py
More file actions
84 lines (63 loc) · 2.39 KB
/
Copy pathsheets.py
File metadata and controls
84 lines (63 loc) · 2.39 KB
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
"""Google Sheets integration — saves extracted invoice data via OAuth."""
import base64
import gspread
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os
from config import GOOGLE_SHEET_ID, OAUTH_CLIENT_SECRET_FILE, OAUTH_TOKEN_FILE
SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
HEADERS = ["Vendor", "Date", "Total Amount", "Currency", "Item Description", "Item Amount"]
def ensure_token_file():
"""On Railway, recreate token.json from a base64 env var if it doesn't exist locally."""
if os.path.exists(OAUTH_TOKEN_FILE):
return
token_b64 = os.environ.get("GOOGLE_TOKEN_B64")
if token_b64:
os.makedirs(os.path.dirname(OAUTH_TOKEN_FILE), exist_ok=True)
with open(OAUTH_TOKEN_FILE, "wb") as f:
f.write(base64.b64decode(token_b64))
def get_credentials():
ensure_token_file()
creds = None
if os.path.exists(OAUTH_TOKEN_FILE):
creds = Credentials.from_authorized_user_file(OAUTH_TOKEN_FILE, SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(OAUTH_CLIENT_SECRET_FILE, SCOPES)
creds = flow.run_local_server(port=0)
with open(OAUTH_TOKEN_FILE, "w") as token_file:
token_file.write(creds.to_json())
return creds
def get_sheet():
creds = get_credentials()
client = gspread.authorize(creds)
sheet = client.open_by_key(GOOGLE_SHEET_ID).sheet1
first_row = sheet.row_values(1)
if first_row != HEADERS:
sheet.update("A1:F1", [HEADERS])
sheet.format("A1:F1", {"textFormat": {"bold": True}})
return sheet
def save_invoice(data: dict):
sheet = get_sheet()
vendor = data.get("vendor") or ""
date = data.get("date") or ""
total = data.get("total_amount") or ""
currency = data.get("currency") or ""
items = data.get("items", [])
if not items:
sheet.append_row([vendor, date, total, currency, "", ""])
return
rows = []
for item in items:
rows.append([
vendor,
date,
total,
currency,
item.get("description", ""),
item.get("amount", ""),
])
sheet.append_rows(rows)