ZeeAI1 commited on
Commit
e212866
·
verified ·
1 Parent(s): c6918d9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +172 -0
app.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+ import json
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ import uuid
5
+ import datetime
6
+
7
+ # Initialize AI model (Mistral-7B)
8
+ model_name = "mistralai/Mixtral-8x7B-Instruct-v0.1"
9
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
10
+ model = AutoModelForCausalLM.from_pretrained(model_name)
11
+
12
+ # Database setup
13
+ conn = sqlite3.connect("erp.db")
14
+ cursor = conn.cursor()
15
+
16
+ # Create tables
17
+ cursor.execute("""
18
+ CREATE TABLE IF NOT EXISTS chart_of_accounts (
19
+ account_id TEXT PRIMARY KEY,
20
+ account_name TEXT,
21
+ account_type TEXT,
22
+ parent_id TEXT,
23
+ allow_budgeting BOOLEAN,
24
+ allow_posting BOOLEAN
25
+ )
26
+ """)
27
+ cursor.execute("""
28
+ CREATE TABLE IF NOT EXISTS journal_entries (
29
+ entry_id TEXT PRIMARY KEY,
30
+ date TEXT,
31
+ debit_account_id TEXT,
32
+ credit_account_id TEXT,
33
+ amount REAL,
34
+ description TEXT
35
+ )
36
+ """)
37
+ conn.commit()
38
+
39
+ # Debit/Credit rules
40
+ ACCOUNT_RULES = {
41
+ "Asset": {"increase": "Debit", "decrease": "Credit"},
42
+ "Liability": {"increase": "Credit", "decrease": "Debit"},
43
+ "Equity": {"increase": "Credit", "decrease": "Debit"},
44
+ "Revenue": {"increase": "Credit", "decrease": "Debit"},
45
+ "Expense": {"increase": "Debit", "decrease": "Credit"}
46
+ }
47
+
48
+ # Sample chart of accounts
49
+ def initialize_chart_of_accounts():
50
+ accounts = [
51
+ ("1", "Fixed Assets", "Asset", None, True, False),
52
+ ("1.1", "Plant", "Asset", "1", True, True),
53
+ ("1.2", "Machinery", "Asset", "1", True, True),
54
+ ("2", "Cash", "Asset", None, True, True),
55
+ ("3", "Accounts Payable", "Liability", None, True, True)
56
+ ]
57
+ cursor.executemany("""
58
+ INSERT OR REPLACE INTO chart_of_accounts
59
+ (account_id, account_name, account_type, parent_id, allow_budgeting, allow_posting)
60
+ VALUES (?, ?, ?, ?, ?, ?)
61
+ """, accounts)
62
+ conn.commit()
63
+
64
+ # Parse prompt using AI model
65
+ def parse_prompt(prompt):
66
+ input_text = f"Parse the following accounting prompt and return a JSON object with debit and credit accounts, amount, and payment method (cash or credit). Prompt: {prompt}"
67
+ inputs = tokenizer(input_text, return_tensors="pt")
68
+ outputs = model.generate(**inputs, max_length=200)
69
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
70
+
71
+ # Assume model returns JSON-like string
72
+ try:
73
+ parsed = json.loads(response)
74
+ return parsed
75
+ except:
76
+ # Fallback parsing
77
+ if "laptop" in prompt.lower() and "cash" in prompt.lower():
78
+ return {
79
+ "debit": {"account": "Laptop", "type": "Asset", "amount": 200},
80
+ "credit": {"account": "Cash", "type": "Asset", "amount": 200},
81
+ "payment_method": "cash"
82
+ }
83
+ return None
84
+
85
+ # Generate journal entry
86
+ def generate_journal_entry(prompt, follow_up_response=None):
87
+ parsed = parse_prompt(prompt)
88
+ if not parsed:
89
+ return "Unable to parse prompt. Please clarify."
90
+
91
+ debit_account = parsed["debit"]["account"]
92
+ credit_account = parsed["credit"]["account"]
93
+ amount = parsed["debit"]["amount"]
94
+ payment_method = parsed.get("payment_method")
95
+
96
+ # Follow-up for payment method
97
+ if not payment_method:
98
+ return "Wonderful, did you buy on credit? (Yes/No)"
99
+
100
+ # Adjust credit account for credit purchases
101
+ if follow_up_response and follow_up_response.lower() == "yes":
102
+ credit_account = "Accounts Payable"
103
+ credit_type = "Liability"
104
+ else:
105
+ credit_type = parsed["credit"]["type"]
106
+
107
+ # Find account IDs
108
+ cursor.execute("SELECT account_id, allow_posting FROM chart_of_accounts WHERE account_name = ?", (debit_account,))
109
+ debit_result = cursor.fetchone()
110
+ cursor.execute("SELECT account_id, allow_posting FROM chart_of_accounts WHERE account_name = ?", (credit_account,))
111
+ credit_result = cursor.fetchone()
112
+
113
+ if not debit_result or not credit_result:
114
+ return "Invalid account names."
115
+ if not debit_result[1] or not credit_result[1]:
116
+ return "Posting not allowed for one or both accounts."
117
+
118
+ # Save journal entry
119
+ entry_id = str(uuid.uuid4())
120
+ date = datetime.datetime.now().isoformat()
121
+ cursor.execute("""
122
+ INSERT INTO journal_entries (entry_id, date, debit_account_id, credit_account_id, amount, description)
123
+ VALUES (?, ?, ?, ?, ?, ?)
124
+ """, (entry_id, date, debit_result[0], credit_result[0], amount, prompt))
125
+ conn.commit()
126
+
127
+ return f"Journal Entry Created: Debit {debit_account} ${amount}, Credit {credit_account} ${amount}"
128
+
129
+ # Generate T-account
130
+ def generate_t_account(account_name):
131
+ cursor.execute("SELECT account_id FROM chart_of_accounts WHERE account_name = ?", (account_name,))
132
+ account_id = cursor.fetchone()
133
+ if not account_id:
134
+ return "Account not found."
135
+
136
+ account_id = account_id[0]
137
+ cursor.execute("""
138
+ SELECT amount, description, 'Debit' as type FROM journal_entries WHERE debit_account_id = ?
139
+ UNION
140
+ SELECT amount, description, 'Credit' as type FROM journal_entries WHERE credit_account_id = ?
141
+ """, (account_id, account_id))
142
+ entries = cursor.fetchall()
143
+
144
+ t_account = f"T-Account for {account_name}\n{'-'*40}\nDebit | Credit\n{'-'*40}\n"
145
+ for amount, desc, entry_type in entries:
146
+ if entry_type == "Debit":
147
+ t_account += f"${amount} | | {desc}\n"
148
+ else:
149
+ t_account += f" | ${amount} | {desc}\n"
150
+
151
+ return t_account
152
+
153
+ # Example usage
154
+ if __name__ == "__main__":
155
+ initialize_chart_of_accounts()
156
+
157
+ # Test prompt
158
+ prompt = "Bought a laptop for $200 on cash"
159
+ result = generate_journal_entry(prompt)
160
+ print(result)
161
+
162
+ # Test T-account
163
+ t_account = generate_t_account("Laptop")
164
+ print(t_account)
165
+
166
+ # Test follow-up
167
+ prompt = "Bought a laptop for $200"
168
+ result = generate_journal_entry(prompt)
169
+ print(result)
170
+ if "did you buy on credit" in result.lower():
171
+ result = generate_journal_entry(prompt, "Yes")
172
+ print(result)