gopichandra commited on
Commit
7964c55
Β·
verified Β·
1 Parent(s): d0be038

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -55
app.py CHANGED
@@ -1,5 +1,5 @@
1
  import os
2
- from paddleocr import PaddleOCR, draw_ocr
3
  from PIL import Image
4
  import gradio as gr
5
  import re
@@ -71,69 +71,71 @@ def extract_attributes(extracted_text):
71
  attributes[readable_attr] = match.group(1).strip()
72
  return attributes
73
 
74
- # Function to fetch and return Salesforce data
75
- def fetch_salesforce_data():
76
  try:
77
  sf = Salesforce(
78
  username=SALESFORCE_USERNAME,
79
  password=SALESFORCE_PASSWORD,
80
- security_token=SALESFORCE_SECURITY_TOKEN,
81
- domain='login'
82
  )
83
 
84
- # SOQL Query
85
- soql_query = "SELECT Product_Name__c, Modal_Name__c, Current_Stocks__c FROM Inventory_Management__c LIMIT 100"
86
- response = sf.query(soql_query)
87
- records = response.get('records', [])
88
 
89
- if not records:
90
- return None, None
 
 
 
 
91
 
92
- df = pd.DataFrame(records)
93
- df.rename(columns={
94
- 'Product_Name__c': 'Product Name',
95
- 'Modal_Name__c': 'Model Name',
96
- 'Current_Stocks__c': 'Current Stocks'
97
- }, inplace=True)
98
- df.drop(columns=['attributes'], inplace=True, errors='ignore')
99
 
100
- return df, generate_bar_graph(df)
 
 
101
 
102
- except Exception as e:
103
- return None, None
104
 
105
- # Function to generate a bar graph from Salesforce data
106
- def generate_bar_graph(df):
107
- try:
108
- fig, ax = plt.subplots(figsize=(12, 8))
109
- df.plot(kind='bar', x="Product Name", y="Current Stocks", ax=ax, legend=False)
110
- ax.set_title("Stock Distribution by Product Name")
111
- ax.set_xlabel("Product Name")
112
- ax.set_ylabel("Current Stocks")
113
- plt.xticks(rotation=45, ha="right", fontsize=10)
114
- plt.tight_layout()
115
- buffer = BytesIO()
116
- plt.savefig(buffer, format="png")
117
- buffer.seek(0)
118
- return Image.open(buffer)
119
- except Exception as e:
120
- return None
121
 
122
- # Function to generate Salesforce data table and graph
123
- def generate_salesforce_data():
124
- df, graph = fetch_salesforce_data()
125
- if df is not None:
126
- return df.to_html(index=False), graph
127
- return "<p>No Data Available</p>", None
128
 
129
- # Function to process images and export to Salesforce
 
 
 
 
 
 
 
 
 
 
 
130
  def process_image(image, mode, entry_type, quantity):
131
  extracted_text = extract_text(image)
132
  if "OCR Error" in extracted_text:
133
  return extracted_text, None
134
 
135
- result = f"πŸ“œ Extracted Text:\n{extracted_text}"
136
- return result, "βœ… Successfully processed image."
 
 
 
137
 
138
  # Gradio App
139
  def app():
@@ -149,17 +151,11 @@ def app():
149
  quantity_input = gr.Number(label="πŸ”’ Quantity", value=1, interactive=True)
150
 
151
  with gr.Column():
152
- image_view = gr.Text(label="πŸ“œ Extracted Data", interactive=False)
153
- result_output = gr.Text(label="πŸ“ Processing Result", interactive=False)
154
- submit_button = gr.Button("πŸ” Process Image")
155
-
156
- with gr.Tab("πŸ“Š Salesforce Data Overview"):
157
- salesforce_table = gr.HTML(label="πŸ“¦ Salesforce Data Table")
158
- salesforce_graph = gr.Image(type="pil", label="πŸ“‰ Stock Distribution Graph")
159
- generate_button = gr.Button("⚑ Generate Data")
160
 
161
  # Button Click Events
162
- generate_button.click(fn=generate_salesforce_data, inputs=[], outputs=[salesforce_table, salesforce_graph])
163
  submit_button.click(fn=process_image, inputs=[image_input, mode_dropdown, entry_type_radio, quantity_input], outputs=[image_view, result_output])
164
 
165
  return interface
 
1
  import os
2
+ from paddleocr import PaddleOCR
3
  from PIL import Image
4
  import gradio as gr
5
  import re
 
71
  attributes[readable_attr] = match.group(1).strip()
72
  return attributes
73
 
74
+ # Function to export extracted data to Salesforce
75
+ def export_to_salesforce(mode, entry_type, quantity, extracted_text):
76
  try:
77
  sf = Salesforce(
78
  username=SALESFORCE_USERNAME,
79
  password=SALESFORCE_PASSWORD,
80
+ security_token=SALESFORCE_SECURITY_TOKEN
 
81
  )
82
 
83
+ # Determine Object & Field Mapping
84
+ object_name, field_name = None, None
 
 
85
 
86
+ if mode == "Entry":
87
+ object_name = "Inventory_Management__c" if entry_type == "Sales" else "Un_Billable__c"
88
+ field_name = "Quantity__c"
89
+ elif mode == "Exit":
90
+ object_name = "Inventory_Management__c" if entry_type == "Sales" else "Un_Billable__c"
91
+ field_name = "Quantity_Sold__c"
92
 
93
+ if not object_name or not field_name:
94
+ return "❌ Invalid mode or entry type."
 
 
 
 
 
95
 
96
+ # Extract Product Name & Attributes
97
+ product_name = match_product_name(extracted_text)
98
+ attributes = extract_attributes(extracted_text)
99
 
100
+ if not product_name:
101
+ return "❌ No matching product found."
102
 
103
+ attributes["Product name"] = product_name
104
+
105
+ # Validate Salesforce fields
106
+ sf_object = sf.__getattr__(object_name)
107
+ schema = sf_object.describe()
108
+ valid_fields = {field["name"] for field in schema["fields"]}
109
+
110
+ filtered_attributes = {ATTRIBUTE_MAPPING[key]: value for key, value in attributes.items() if ATTRIBUTE_MAPPING[key] in valid_fields}
111
+ filtered_attributes[field_name] = quantity
 
 
 
 
 
 
 
112
 
113
+ # Check if record exists
114
+ query = f"SELECT Id FROM {object_name} WHERE Product_Name__c = '{product_name}' LIMIT 1"
115
+ response = sf.query(query)
 
 
 
116
 
117
+ if response["records"]:
118
+ record_id = response["records"][0]["Id"]
119
+ sf_object.update(record_id, filtered_attributes)
120
+ return f"βœ… Updated record for '{product_name}' in {object_name}."
121
+ else:
122
+ sf_object.create(filtered_attributes)
123
+ return f"βœ… Created new record in {object_name} for '{product_name}'."
124
+
125
+ except Exception as e:
126
+ return f"❌ Error exporting data to Salesforce: {str(e)}"
127
+
128
+ # Function to process images, extract attributes, and export to Salesforce
129
  def process_image(image, mode, entry_type, quantity):
130
  extracted_text = extract_text(image)
131
  if "OCR Error" in extracted_text:
132
  return extracted_text, None
133
 
134
+ attributes = extract_attributes(extracted_text)
135
+ attributes_list = "\n".join([f"{key}: {value}" for key, value in attributes.items()])
136
+
137
+ result = export_to_salesforce(mode, entry_type, quantity, extracted_text)
138
+ return f"πŸ“œ Extracted Attributes:\n{attributes_list}", result
139
 
140
  # Gradio App
141
  def app():
 
151
  quantity_input = gr.Number(label="πŸ”’ Quantity", value=1, interactive=True)
152
 
153
  with gr.Column():
154
+ image_view = gr.Text(label="πŸ“œ Extracted Attributes", interactive=False)
155
+ result_output = gr.Text(label="πŸ“ Salesforce Export Result", interactive=False)
156
+ submit_button = gr.Button("πŸ” Process & Export")
 
 
 
 
 
157
 
158
  # Button Click Events
 
159
  submit_button.click(fn=process_image, inputs=[image_input, mode_dropdown, entry_type_radio, quantity_input], outputs=[image_view, result_output])
160
 
161
  return interface