Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -19,12 +19,13 @@ import random
|
|
| 19 |
CLIENT_ID = "1000.SIMKGAO5719K0TQ0QZQ31ZU57RLFNQ"
|
| 20 |
CLIENT_SECRET = "60b329b4fe51930abee900cba6524ec7332cd67e06"
|
| 21 |
|
| 22 |
-
# ***
|
| 23 |
REFRESH_TOKEN = "1000.fcbd3eb6544c48591ceb462eefe439e1.e6dacb8875fec5fa150596fa44eb9326"
|
| 24 |
-
ORGANIZATION_ID = "
|
| 25 |
|
|
|
|
| 26 |
AUTH_URL = "https://accounts.zoho.in/oauth/v2/token"
|
| 27 |
-
API_BASE = "https://www.zohoapis.in/
|
| 28 |
MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"
|
| 29 |
|
| 30 |
# ==========================================
|
|
@@ -46,99 +47,70 @@ def get_zoho_headers():
|
|
| 46 |
except Exception as e:
|
| 47 |
return None, str(e)
|
| 48 |
|
| 49 |
-
def
|
| 50 |
-
"""
|
| 51 |
-
|
| 52 |
-
|
|
|
|
| 53 |
|
| 54 |
-
# 1.
|
| 55 |
-
try:
|
| 56 |
-
params = {"organization_id": ORGANIZATION_ID}
|
| 57 |
-
resp = requests.get(url, headers=headers, params=params)
|
| 58 |
-
accounts = resp.json().get("chartofaccounts", [])
|
| 59 |
-
|
| 60 |
-
for acc in accounts:
|
| 61 |
-
if "expense" in acc["account_type"].lower():
|
| 62 |
-
print(f"✅ Found Account: {acc['account_name']}")
|
| 63 |
-
return acc["account_id"], "Found"
|
| 64 |
-
except: pass
|
| 65 |
-
|
| 66 |
-
# 2. Create if missing (FIXED: Removed currency_id)
|
| 67 |
-
print("⚠️ No Expense Account found. Creating 'MCP Expenses'...")
|
| 68 |
-
create_payload = {
|
| 69 |
-
"account_name": "MCP Automated Expenses",
|
| 70 |
-
"account_type": "expense" # No currency_id needed
|
| 71 |
-
}
|
| 72 |
-
create_resp = requests.post(url, headers=headers, params={"organization_id": ORGANIZATION_ID}, json=create_payload)
|
| 73 |
-
|
| 74 |
-
if create_resp.status_code == 201:
|
| 75 |
-
new_id = create_resp.json().get("chartofaccount", {}).get("account_id")
|
| 76 |
-
print(f"✅ Created New Account: {new_id}")
|
| 77 |
-
return new_id, "Created"
|
| 78 |
-
else:
|
| 79 |
-
# RETURN RAW ERROR SO WE CAN SEE IT
|
| 80 |
-
return None, f"Zoho Account Create Failed: {create_resp.text}"
|
| 81 |
-
|
| 82 |
-
def find_or_create_vendor(vendor_name, headers):
|
| 83 |
-
if not vendor_name or len(str(vendor_name)) < 2: vendor_name = "MCP Vendor"
|
| 84 |
search_url = f"{API_BASE}/contacts"
|
| 85 |
-
|
| 86 |
try:
|
| 87 |
-
params = {
|
|
|
|
|
|
|
|
|
|
| 88 |
resp = requests.get(search_url, headers=headers, params=params)
|
| 89 |
contacts = resp.json().get("contacts", [])
|
| 90 |
-
if contacts:
|
|
|
|
|
|
|
| 91 |
except: pass
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
create_resp = requests.post(search_url, headers=headers, params={"organization_id": ORGANIZATION_ID}, json=create_payload)
|
| 96 |
|
| 97 |
if create_resp.status_code == 201:
|
| 98 |
-
|
|
|
|
| 99 |
else:
|
| 100 |
return None, f"Contact Error: {create_resp.text}"
|
| 101 |
|
| 102 |
-
def
|
|
|
|
|
|
|
|
|
|
| 103 |
headers, error = get_zoho_headers()
|
| 104 |
if error: return error
|
| 105 |
|
| 106 |
-
# 1.
|
| 107 |
-
|
| 108 |
-
if not
|
| 109 |
-
|
| 110 |
-
# 2. Vendor
|
| 111 |
-
vid, v_status = find_or_create_vendor(payload.get("vendor_name_raw"), headers)
|
| 112 |
-
if not vid: return f"❌ Vendor Error: {v_status}"
|
| 113 |
|
| 114 |
-
#
|
| 115 |
-
|
| 116 |
-
if not bill_num or str(bill_num).lower() == "null":
|
| 117 |
-
bill_num = f"MCP-{random.randint(1000,9999)}"
|
| 118 |
-
|
| 119 |
final_json = {
|
| 120 |
-
"
|
| 121 |
-
"bill_number": str(bill_num),
|
| 122 |
"date": payload.get("date", datetime.date.today().strftime("%Y-%m-%d")),
|
| 123 |
-
"line_items": [
|
| 124 |
-
{
|
| 125 |
-
"account_id": account_id,
|
| 126 |
-
"name": item["name"],
|
| 127 |
-
"rate": item["rate"],
|
| 128 |
-
"quantity": 1
|
| 129 |
-
} for item in payload.get("line_items", [])
|
| 130 |
-
],
|
| 131 |
"status": "draft"
|
| 132 |
}
|
| 133 |
|
| 134 |
-
|
| 135 |
-
|
|
|
|
| 136 |
resp = requests.post(url, headers=headers, json=final_json)
|
| 137 |
|
| 138 |
if resp.status_code == 201:
|
| 139 |
-
|
| 140 |
-
link = f"https://
|
| 141 |
-
return f"✅ SUCCESS!
|
| 142 |
else:
|
| 143 |
return f"❌ Zoho API Error: {resp.text}"
|
| 144 |
|
|
@@ -164,9 +136,11 @@ def perform_ocr(file_obj):
|
|
| 164 |
|
| 165 |
def query_ai(text):
|
| 166 |
if not model: return {"vendor_name": "Unknown", "total": 0}
|
| 167 |
-
|
|
|
|
| 168 |
inputs = tokenizer(prompt, return_tensors="pt")
|
| 169 |
out = model.generate(**inputs, max_new_tokens=200)
|
|
|
|
| 170 |
try:
|
| 171 |
json_str = tokenizer.decode(out[0]).split("```json")[1].split("```")[0].strip()
|
| 172 |
data = json.loads(json_str)
|
|
@@ -182,22 +156,21 @@ def run(file):
|
|
| 182 |
except: rate = 0
|
| 183 |
|
| 184 |
payload = {
|
| 185 |
-
"vendor_name_raw": data.get("vendor_name"),
|
| 186 |
-
"invoice_number": data.get("invoice_number"),
|
| 187 |
"date": data.get("invoice_date"),
|
| 188 |
"line_items": [{"name": data.get("item_desc", "Service"), "rate": rate}]
|
| 189 |
}
|
| 190 |
|
| 191 |
-
return img,
|
| 192 |
|
| 193 |
# ==========================================
|
| 194 |
# 4. UI
|
| 195 |
# ==========================================
|
| 196 |
-
with gr.Blocks(title="Zoho
|
| 197 |
-
gr.Markdown("## 🧾 MCP Agent -> Zoho
|
| 198 |
with gr.Row():
|
| 199 |
-
f_in = gr.File(label="
|
| 200 |
-
btn = gr.Button("
|
| 201 |
out_img = gr.Image(label="View", height=300)
|
| 202 |
out_res = gr.Textbox(label="Status")
|
| 203 |
btn.click(run, f_in, [out_img, out_res])
|
|
|
|
| 19 |
CLIENT_ID = "1000.SIMKGAO5719K0TQ0QZQ31ZU57RLFNQ"
|
| 20 |
CLIENT_SECRET = "60b329b4fe51930abee900cba6524ec7332cd67e06"
|
| 21 |
|
| 22 |
+
# *** ENSURE TOKEN HAS SCOPE: ZohoInvoice.fullaccess.ALL ***
|
| 23 |
REFRESH_TOKEN = "1000.fcbd3eb6544c48591ceb462eefe439e1.e6dacb8875fec5fa150596fa44eb9326"
|
| 24 |
+
ORGANIZATION_ID = "60058860935"
|
| 25 |
|
| 26 |
+
# SWITCHED TO ZOHO INVOICE API
|
| 27 |
AUTH_URL = "https://accounts.zoho.in/oauth/v2/token"
|
| 28 |
+
API_BASE = "https://www.zohoapis.in/invoice/v3"
|
| 29 |
MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"
|
| 30 |
|
| 31 |
# ==========================================
|
|
|
|
| 47 |
except Exception as e:
|
| 48 |
return None, str(e)
|
| 49 |
|
| 50 |
+
def find_or_create_customer(name, headers):
|
| 51 |
+
"""
|
| 52 |
+
Doc: https://www.zoho.com/invoice/api/v3/contacts/#create-a-contact
|
| 53 |
+
"""
|
| 54 |
+
if not name or len(str(name)) < 2: name = "MCP Customer"
|
| 55 |
|
| 56 |
+
# 1. Search for Existing Customer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
search_url = f"{API_BASE}/contacts"
|
|
|
|
| 58 |
try:
|
| 59 |
+
params = {
|
| 60 |
+
"organization_id": ORGANIZATION_ID,
|
| 61 |
+
"contact_name_contains": name
|
| 62 |
+
}
|
| 63 |
resp = requests.get(search_url, headers=headers, params=params)
|
| 64 |
contacts = resp.json().get("contacts", [])
|
| 65 |
+
if contacts:
|
| 66 |
+
print(f"✅ Found Customer: {contacts[0]['contact_name']}")
|
| 67 |
+
return contacts[0]["contact_id"], "Existing"
|
| 68 |
except: pass
|
| 69 |
|
| 70 |
+
# 2. Create New Customer
|
| 71 |
+
print(f"🆕 Creating Customer: {name}")
|
| 72 |
+
create_payload = {
|
| 73 |
+
"contact_name": name,
|
| 74 |
+
"contact_type": "customer", # REQUIRED for Invoice API
|
| 75 |
+
"payment_terms": 15 # Optional: Net 15
|
| 76 |
+
}
|
| 77 |
create_resp = requests.post(search_url, headers=headers, params={"organization_id": ORGANIZATION_ID}, json=create_payload)
|
| 78 |
|
| 79 |
if create_resp.status_code == 201:
|
| 80 |
+
new_id = create_resp.json().get("contact", {}).get("contact_id")
|
| 81 |
+
return new_id, "Created New"
|
| 82 |
else:
|
| 83 |
return None, f"Contact Error: {create_resp.text}"
|
| 84 |
|
| 85 |
+
def push_invoice_to_zoho(payload):
|
| 86 |
+
"""
|
| 87 |
+
Doc: https://www.zoho.com/invoice/api/v3/invoices/#create-an-invoice
|
| 88 |
+
"""
|
| 89 |
headers, error = get_zoho_headers()
|
| 90 |
if error: return error
|
| 91 |
|
| 92 |
+
# 1. Get/Create Customer
|
| 93 |
+
cid, c_status = find_or_create_customer(payload.get("vendor_name_raw"), headers)
|
| 94 |
+
if not cid: return f"❌ Customer Logic Failed: {c_status}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
# 2. Construct Invoice Payload
|
| 97 |
+
# Zoho Invoice requires 'customer_id' and 'line_items'
|
|
|
|
|
|
|
|
|
|
| 98 |
final_json = {
|
| 99 |
+
"customer_id": cid,
|
|
|
|
| 100 |
"date": payload.get("date", datetime.date.today().strftime("%Y-%m-%d")),
|
| 101 |
+
"line_items": payload.get("line_items", []),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
"status": "draft"
|
| 103 |
}
|
| 104 |
|
| 105 |
+
# 3. Push to /invoices
|
| 106 |
+
print(f"🚀 Creating Invoice for {cid}...")
|
| 107 |
+
url = f"{API_BASE}/invoices?organization_id={ORGANIZATION_ID}"
|
| 108 |
resp = requests.post(url, headers=headers, json=final_json)
|
| 109 |
|
| 110 |
if resp.status_code == 201:
|
| 111 |
+
inv = resp.json().get("invoice", {})
|
| 112 |
+
link = f"https://invoice.zoho.in/app/{ORGANIZATION_ID}#/invoices/{inv.get('invoice_id')}"
|
| 113 |
+
return f"✅ SUCCESS! Invoice Created.\nNumber: {inv.get('invoice_number')}\nCustomer: {c_status}\nLink: {link}"
|
| 114 |
else:
|
| 115 |
return f"❌ Zoho API Error: {resp.text}"
|
| 116 |
|
|
|
|
| 136 |
|
| 137 |
def query_ai(text):
|
| 138 |
if not model: return {"vendor_name": "Unknown", "total": 0}
|
| 139 |
+
|
| 140 |
+
prompt = f"<|im_start|>user\nExtract JSON: vendor_name, invoice_date (YYYY-MM-DD), total, item_desc\nText:\n{text[:1000]}<|im_end|>\n<|im_start|>assistant\n```json"
|
| 141 |
inputs = tokenizer(prompt, return_tensors="pt")
|
| 142 |
out = model.generate(**inputs, max_new_tokens=200)
|
| 143 |
+
|
| 144 |
try:
|
| 145 |
json_str = tokenizer.decode(out[0]).split("```json")[1].split("```")[0].strip()
|
| 146 |
data = json.loads(json_str)
|
|
|
|
| 156 |
except: rate = 0
|
| 157 |
|
| 158 |
payload = {
|
| 159 |
+
"vendor_name_raw": data.get("vendor_name"), # Used as Customer Name here
|
|
|
|
| 160 |
"date": data.get("invoice_date"),
|
| 161 |
"line_items": [{"name": data.get("item_desc", "Service"), "rate": rate}]
|
| 162 |
}
|
| 163 |
|
| 164 |
+
return img, push_invoice_to_zoho(payload)
|
| 165 |
|
| 166 |
# ==========================================
|
| 167 |
# 4. UI
|
| 168 |
# ==========================================
|
| 169 |
+
with gr.Blocks(title="Zoho Invoice Agent") as demo:
|
| 170 |
+
gr.Markdown("## 🧾 MCP Agent -> Zoho Invoice API")
|
| 171 |
with gr.Row():
|
| 172 |
+
f_in = gr.File(label="Upload Document")
|
| 173 |
+
btn = gr.Button("Create Invoice", variant="primary")
|
| 174 |
out_img = gr.Image(label="View", height=300)
|
| 175 |
out_res = gr.Textbox(label="Status")
|
| 176 |
btn.click(run, f_in, [out_img, out_res])
|