rishisriv-bh commited on
Commit
0d231e5
Β·
verified Β·
1 Parent(s): 7d8b7da

csv only submissions

Browse files
Files changed (1) hide show
  1. app_chatgpt.py +38 -47
app_chatgpt.py CHANGED
@@ -1,15 +1,11 @@
1
  import openai
2
- import openpyxl
3
- import PyPDF2
4
  import pandas as pd
5
- from PIL import Image
6
- import pytesseract
7
- import io
8
  import os
9
  import gradio as gr
10
  import boto3
11
  import uuid
12
 
 
13
  openai.api_key = os.environ.get("Open_ai_key")
14
  bucket_name = os.environ.get("Bucket_name")
15
 
@@ -18,32 +14,28 @@ session = boto3.Session(
18
  aws_secret_access_key=os.getenv("secret_access_key")
19
  )
20
 
21
-
22
  def upload_files_to_s3(erp_file_path, external_file_path, content, bucket_name):
23
  s3 = session.client("s3")
24
-
25
  session_id = str(uuid.uuid4())
26
 
27
- # Create filenames with UUID
28
- erp_filename = f"{os.path.splitext(os.path.basename(erp_file_path))[0]}_{session_id}{os.path.splitext(erp_file_path)[1]}"
29
- bank_filename = f"{os.path.splitext(os.path.basename(external_file_path))[0]}_{session_id}{os.path.splitext(external_file_path)[1]}"
30
  txt_filename = f"{session_id}.txt"
31
 
32
- # Write content to a local .txt file
33
  with open(txt_filename, "w", encoding="utf-8") as file:
34
  file.write(content)
35
 
36
- # Define S3 keys (organized into folders)
37
  erp_s3_key = f"ERP Statements/{erp_filename}"
38
  bank_s3_key = f"Bank Statements/{bank_filename}"
39
  txt_s3_key = f"Reconciliation Results/{txt_filename}"
40
 
41
- # Upload all 3 files to S3
42
  s3.upload_file(erp_file_path, bucket_name, erp_s3_key)
43
  s3.upload_file(external_file_path, bucket_name, bank_s3_key)
44
  s3.upload_file(txt_filename, bucket_name, txt_s3_key)
45
 
46
- # Optionally clean up the local .txt file
47
  os.remove(txt_filename)
48
 
49
  return {
@@ -54,38 +46,22 @@ def upload_files_to_s3(erp_file_path, external_file_path, content, bucket_name):
54
  }
55
 
56
 
 
57
  def extract_transactions(file):
58
- """Extract raw text content from various supported file formats."""
59
  filename = file.name.lower()
 
 
 
 
60
 
61
  try:
62
- if filename.endswith((".xlsx", ".xls")):
63
- workbook = openpyxl.load_workbook(file.name, data_only=True)
64
- sheet = workbook.active
65
- return "\n".join(
66
- "\t".join(str(cell.value or "") for cell in row)
67
- for row in sheet.iter_rows()
68
- )
69
-
70
- elif filename.endswith(".csv"):
71
- df = pd.read_csv(file.name)
72
- return df.to_string(index=False)
73
-
74
- elif filename.endswith(".pdf"):
75
- reader = PyPDF2.PdfReader(file)
76
- return "\n".join(page.extract_text() or "" for page in reader.pages)
77
-
78
- elif filename.endswith((".jpg", ".jpeg", ".png")):
79
- image = Image.open(io.BytesIO(file.read()))
80
- return pytesseract.image_to_string(image)
81
-
82
- else:
83
- raise ValueError("Unsupported file format.")
84
-
85
  except Exception as e:
86
  raise ValueError(f"Error processing {file.name}: {e}")
87
 
88
 
 
89
  def reconcile_statements_openai(erp_file, external_file):
90
  yield "⏳ Processing your request...", ""
91
 
@@ -120,7 +96,7 @@ Please follow this format in your response:
120
  Here is the ERP data:
121
  {erp_data}
122
  ---
123
- Here is the External (Bank or Vendor) data::
124
  {external_data}
125
  """
126
 
@@ -144,7 +120,8 @@ Here is the External (Bank or Vendor) data::
144
  """
145
  yield "βœ… Done!", html
146
 
147
- s3_info = upload_files_to_s3(
 
148
  erp_file_path=erp_file,
149
  external_file_path=external_file,
150
  content=html,
@@ -155,7 +132,7 @@ Here is the External (Bank or Vendor) data::
155
  yield "❌ Error occurred", f"<h3>Error</h3><pre>{e}</pre>"
156
 
157
 
158
- # Gradio UI
159
  with gr.Blocks(css="""
160
  #company-logo {
161
  width: 25%;
@@ -165,18 +142,32 @@ with gr.Blocks(css="""
165
  """) as iface:
166
  gr.Image("logo_Icon.png", elem_id="company-logo", label="Beiing Human")
167
  gr.Markdown("## πŸ“Š ERP vs Bank/Vendor Reconciliation Tool")
 
 
 
 
 
 
168
  with gr.Row():
169
- erp_file = gr.File(label="πŸ“ Upload ERP Statement", type="filepath")
170
- external_file = gr.File(label="🏦 Upload Bank or Vendor Statement", type="filepath")
 
 
 
 
 
 
 
 
 
171
  btn = gr.Button("πŸ” Reconcile")
 
172
  with gr.Row():
173
  support_btn = gr.Button(
174
  "πŸ“§ Contact Support",
175
  link="mailto:[email protected]?subject=Support%20Request&body=Hi%20Beiing%20Human%20Team%2C%0A%0AI%20have%20a%20question%20about%20the%20reconciliation%20tool.%20Here%20are%20the%20details..."
176
  )
177
- support_email_display = gr.Markdown("πŸ“¬ Or email us at: `[email protected]` (copy & paste)")
178
-
179
- # support_btn = gr.Button("πŸ“§ Contact Support: [email protected]", link="mailto:[email protected]?subject=Support%20Request&body=Hi%20Beiing%20Human%20Team%2C%0A%0AI%20have%20a%20question%20about%20the%20reconciliation%20tool.%20Here%20are%20the%20details...")
180
 
181
  status = gr.Markdown()
182
  result = gr.HTML()
@@ -187,4 +178,4 @@ with gr.Blocks(css="""
187
  outputs=[status, result]
188
  )
189
 
190
- iface.launch()
 
1
  import openai
 
 
2
  import pandas as pd
 
 
 
3
  import os
4
  import gradio as gr
5
  import boto3
6
  import uuid
7
 
8
+ # βœ… Load your secrets from environment
9
  openai.api_key = os.environ.get("Open_ai_key")
10
  bucket_name = os.environ.get("Bucket_name")
11
 
 
14
  aws_secret_access_key=os.getenv("secret_access_key")
15
  )
16
 
17
+ # βœ… Upload reconciled results and original files to S3
18
  def upload_files_to_s3(erp_file_path, external_file_path, content, bucket_name):
19
  s3 = session.client("s3")
 
20
  session_id = str(uuid.uuid4())
21
 
22
+ erp_filename = f"{os.path.splitext(os.path.basename(erp_file_path))[0]}_{session_id}.csv"
23
+ bank_filename = f"{os.path.splitext(os.path.basename(external_file_path))[0]}_{session_id}.csv"
 
24
  txt_filename = f"{session_id}.txt"
25
 
26
+ # Write reconciliation output to local file
27
  with open(txt_filename, "w", encoding="utf-8") as file:
28
  file.write(content)
29
 
30
+ # Define S3 keys
31
  erp_s3_key = f"ERP Statements/{erp_filename}"
32
  bank_s3_key = f"Bank Statements/{bank_filename}"
33
  txt_s3_key = f"Reconciliation Results/{txt_filename}"
34
 
 
35
  s3.upload_file(erp_file_path, bucket_name, erp_s3_key)
36
  s3.upload_file(external_file_path, bucket_name, bank_s3_key)
37
  s3.upload_file(txt_filename, bucket_name, txt_s3_key)
38
 
 
39
  os.remove(txt_filename)
40
 
41
  return {
 
46
  }
47
 
48
 
49
+ # βœ… Extract transactions from CSV only
50
  def extract_transactions(file):
 
51
  filename = file.name.lower()
52
+ if not filename.endswith(".csv"):
53
+ raise ValueError(
54
+ f"Unsupported file format: {filename}. Please upload a CSV file only."
55
+ )
56
 
57
  try:
58
+ df = pd.read_csv(file.name)
59
+ return df.to_string(index=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  except Exception as e:
61
  raise ValueError(f"Error processing {file.name}: {e}")
62
 
63
 
64
+ # βœ… Reconcile the statements using OpenAI
65
  def reconcile_statements_openai(erp_file, external_file):
66
  yield "⏳ Processing your request...", ""
67
 
 
96
  Here is the ERP data:
97
  {erp_data}
98
  ---
99
+ Here is the External (Bank or Vendor) data:
100
  {external_data}
101
  """
102
 
 
120
  """
121
  yield "βœ… Done!", html
122
 
123
+ # βœ… Upload the files + result to S3
124
+ upload_files_to_s3(
125
  erp_file_path=erp_file,
126
  external_file_path=external_file,
127
  content=html,
 
132
  yield "❌ Error occurred", f"<h3>Error</h3><pre>{e}</pre>"
133
 
134
 
135
+ # βœ… Gradio UI for CSV-only
136
  with gr.Blocks(css="""
137
  #company-logo {
138
  width: 25%;
 
142
  """) as iface:
143
  gr.Image("logo_Icon.png", elem_id="company-logo", label="Beiing Human")
144
  gr.Markdown("## πŸ“Š ERP vs Bank/Vendor Reconciliation Tool")
145
+
146
+ gr.Markdown(
147
+ "⚠️ **Important:** Please upload your statements as CSV files only. "
148
+ "Include columns: **Date**, **Amount**, **Description**."
149
+ )
150
+
151
  with gr.Row():
152
+ erp_file = gr.File(
153
+ label="πŸ“ Upload ERP Statement (CSV only)",
154
+ type="filepath",
155
+ file_types=[".csv"]
156
+ )
157
+ external_file = gr.File(
158
+ label="🏦 Upload Bank or Vendor Statement (CSV only)",
159
+ type="filepath",
160
+ file_types=[".csv"]
161
+ )
162
+
163
  btn = gr.Button("πŸ” Reconcile")
164
+
165
  with gr.Row():
166
  support_btn = gr.Button(
167
  "πŸ“§ Contact Support",
168
  link="mailto:[email protected]?subject=Support%20Request&body=Hi%20Beiing%20Human%20Team%2C%0A%0AI%20have%20a%20question%20about%20the%20reconciliation%20tool.%20Here%20are%20the%20details..."
169
  )
170
+ gr.Markdown("πŸ“¬ Or email us at: `[email protected]` (copy & paste)")
 
 
171
 
172
  status = gr.Markdown()
173
  result = gr.HTML()
 
178
  outputs=[status, result]
179
  )
180
 
181
+ iface.launch()