gopichandra commited on
Commit
f930989
·
verified ·
1 Parent(s): 731bd25

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -131
app.py CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  import os
2
  from paddleocr import PaddleOCR
3
  from PIL import Image
@@ -145,81 +148,11 @@ def extract_attributes(extracted_text):
145
 
146
  return attributes
147
 
148
- # Function to filter attributes for valid Salesforce fields📊
149
  def filter_valid_attributes(attributes, valid_fields):
150
  return {ATTRIBUTE_MAPPING[key]: value for key, value in attributes.items() if ATTRIBUTE_MAPPING[key] in valid_fields}
151
 
152
-
153
- #📊 Function to interact with Salesforce based on mode and type
154
-
155
-
156
- import os
157
- from paddleocr import PaddleOCR
158
- from PIL import Image
159
- import gradio as gr
160
- import requests
161
- import re
162
- from simple_salesforce import Salesforce
163
- import pandas as pd
164
- import matplotlib.pyplot as plt
165
- from io import BytesIO
166
- from fuzzywuzzy import process
167
- import kaleido # Ensure kaleido is imported
168
-
169
- # Salesforce credentials
170
- SALESFORCE_USERNAME = "venkatramana@sandbox.com"
171
- SALESFORCE_PASSWORD = "Venkat12345@"
172
- SALESFORCE_SECURITY_TOKEN = "GhcJJmjBEefdnukJoz4CAQlR"
173
-
174
- # Initialize PaddleOCR
175
- ocr = PaddleOCR(use_angle_cls=True, lang='en')
176
-
177
- # Function to extract text using PaddleOCR
178
- def extract_text(image):
179
- result = ocr.ocr(image)
180
- extracted_text = []
181
- for line in result[0]:
182
- extracted_text.append(line[1][0])
183
- return "\n".join(extracted_text)
184
-
185
- # Function to match product name using fuzzy matching
186
- def match_product_name(extracted_text):
187
- best_match = None
188
- best_score = 0
189
- PRODUCT_NAMES = [
190
- "Centrifugal mono block pump", "SINGLE PHASE MOTOR STARTER", "EasyPact EZC 100",
191
- "Openwell Submersible Pumpset", "Electric Motor", "Self Priming Pump",
192
- "Control panel for single phase submersible pumps", "MOTOR", "Submersible pump set",
193
- "Fusion submersible pump set", "DCT", "Shock proof water proof", "CG COMMERCIAL MOTORS", "Fusion",
194
- "control panel for single phase submerisible pumps", "single phase digital starter dry run and timer panel",
195
- "5HP AV1 XL Kirloskar Pump", "Phase stainless steel submersible pump", "Submersible pump", "WB15X",
196
- "Vtype self priming pump", "SP SHINE DISC", "havells submersible pump",
197
- "Havells open well Submersible pump", "Bertolini pump CK3 90pp",
198
- "WPA 772 Water Pump Assy", "bertolini TTL triplex high pressure plunger pumps",
199
- "Generic plunger high pressure pump", "Apple Normal, Banana",
200
- "Cast Iron KSb centrifugal pump", "5.5kw Water Pump",
201
- "KSB reliable i line centrifuged pumps", "Apple Normal, Orange, Banana",
202
- "Positive API 6745 hydraulic diaphragm pump", "1/2 inch Fuel Hose Pipe", "Kirloskar Water Pump",
203
- "Rotodel motor pump", "PVC Electrical Insulation Materials",
204
- "Electric kirloskar domestic water pump", "Electrical Insulation Materials",
205
- "sellowell motor pump", "bhupathi submersible pump set",
206
- "Flowshine Submersible pump set", "Index submersible pump",
207
- "Wintoss Plastic Electric Switch Board", "Electric 18 watt ujagar cooler pump",
208
- "Generator Service", "LG WM FHT1207ZWL, LG REF GL-S292RSCY",
209
- "Water tank, Filters, Water Pump", "MS Control Submersible Panel",
210
- "Centrifugal Monoblock Pumps", "Electric Motor with Pump BodyBlue and White",
211
- "Various Repair and Maintenance Parts", "Earthmax Pump",
212
- "Water Tank, Filters, Water Pump", "Centrifugal Water Pump for Agriculture",
213
- "mono block pumps"
214
- ]
215
- for line in extracted_text.split("\n"):
216
- match, score = process.extractOne(line, PRODUCT_NAMES)
217
- if score > best_score:
218
- best_match = match
219
- best_score = score
220
- return best_match if best_score >= 70 else None # Threshold of 70 for a match
221
-
222
- # Function to interact with Salesforce based on mode and type
223
  def interact_with_salesforce(mode, entry_type, quantity, extracted_text):
224
  try:
225
  sf = Salesforce(
@@ -232,6 +165,7 @@ def interact_with_salesforce(mode, entry_type, quantity, extracted_text):
232
  object_name = None
233
  field_name = None
234
  product_field_name = "Product_Name__c"
 
235
 
236
  if mode == "Entry":
237
  if entry_type == "Sales":
@@ -240,16 +174,6 @@ def interact_with_salesforce(mode, entry_type, quantity, extracted_text):
240
  elif entry_type == "Non-Sales":
241
  object_name = "UNBILLING_DATA__c"
242
  field_name = "TotalQuantity__c"
243
-
244
- # Extract product name
245
- product_name = match_product_name(extracted_text)
246
- if not product_name:
247
- return "Product name could not be matched from the extracted text."
248
-
249
- # Creating a new record
250
- sf.__getattr__(object_name).create({product_field_name: product_name, field_name: quantity})
251
- return f"✅ Record created in {object_name} with Product: '{product_name}', Quantity: {quantity}."
252
-
253
  elif mode == "Exit":
254
  if entry_type == "Sales":
255
  object_name = "Inventory_Management__c"
@@ -258,70 +182,97 @@ def interact_with_salesforce(mode, entry_type, quantity, extracted_text):
258
  object_name = "Un_Billable__c"
259
  field_name = "Sold_Out__c"
260
 
261
- # Extract product name
262
- product_name = match_product_name(extracted_text)
263
- if not product_name:
264
- return "Product name could not be matched from the extracted text."
 
 
 
265
 
266
- query = f"SELECT Id, {field_name} FROM {object_name} WHERE {product_field_name} = '{product_name}' LIMIT 1"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
  response = sf.query(query)
268
 
269
  if response["records"]:
270
  record_id = response["records"][0]["Id"]
271
- updated_quantity = quantity
272
- sf.__getattr__(object_name).update(record_id, {field_name: updated_quantity})
273
- return f"✅ Updated record for product '{product_name}' in {object_name}. New {field_name}: {updated_quantity}."
274
  else:
275
- return f"❌ No matching record found for product '{product_name}' in {object_name}."
 
 
 
 
 
 
 
276
 
277
  except Exception as e:
278
  return f"❌ Error interacting with Salesforce: {str(e)}"
279
-
280
- # Function to pull structured data from Salesforce and display as a table
281
- def pull_data_from_salesforce():
282
- try:
283
- sf = Salesforce(
284
  username=SALESFORCE_USERNAME,
285
  password=SALESFORCE_PASSWORD,
286
  security_token=SALESFORCE_SECURITY_TOKEN
287
  )
288
-
289
- query = "SELECT Product_Name__c, Modal_Name__c, Current_Stocks__c FROM Inventory_Management__c LIMIT 100"
290
- response = sf.query_all(query)
291
-
292
- records = response.get("records", [])
293
- if not records:
294
- return "No data found in Salesforce.", None, None, None
295
-
296
- df = pd.DataFrame(records)
297
- df = df.drop(columns=['attributes'], errors='ignore')
298
 
299
  # Rename columns for better readability
300
- df.rename(columns={
301
- "Product_Name__c": "Product Name",
302
- "Modal_Name__c": "Model Name",
303
- "Current_Stocks__c": "Current Stocks"
304
- }, inplace=True)
305
-
306
- excel_path = "salesforce_data.xlsx"
307
- df.to_excel(excel_path, index=False)
308
-
309
- # Generate interactive vertical bar graph using Matplotlib
310
- fig, ax = plt.subplots(figsize=(12, 8))
311
- df.plot(kind='bar', x="Product Name", y="Current Stocks", ax=ax, legend=False)
312
- ax.set_title("Stock Distribution by Product Name")
313
- ax.set_xlabel("Product Name")
314
- ax.set_ylabel("Current Stocks")
315
- plt.xticks(rotation=45, ha="right", fontsize=10)
316
- plt.tight_layout()
317
- buffer = BytesIO()
318
- plt.savefig(buffer, format="png")
319
- buffer.seek(0)
320
- img = Image.open(buffer)
321
-
322
- return "Data successfully retrieved.", df, excel_path, img
323
- except Exception as e:
324
- return f"Error fetching data: {str(e)}", None, None, None
325
 
326
  # Unified function to handle image processing and Salesforce interaction
327
  def process_image(image, mode, entry_type, quantity):
 
1
+ HUGGING FACE ALL FUNCTIONALITIES WORKING
2
+
3
+
4
  import os
5
  from paddleocr import PaddleOCR
6
  from PIL import Image
 
148
 
149
  return attributes
150
 
151
+ # Function to filter attributes for valid Salesforce fields
152
  def filter_valid_attributes(attributes, valid_fields):
153
  return {ATTRIBUTE_MAPPING[key]: value for key, value in attributes.items() if ATTRIBUTE_MAPPING[key] in valid_fields}
154
 
155
+ #📊 Function to interact with Salesforce based on mode and type
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  def interact_with_salesforce(mode, entry_type, quantity, extracted_text):
157
  try:
158
  sf = Salesforce(
 
165
  object_name = None
166
  field_name = None
167
  product_field_name = "Product_Name__c"
168
+ model_field_name = "Modal_Name__c" # Correct field for model name
169
 
170
  if mode == "Entry":
171
  if entry_type == "Sales":
 
174
  elif entry_type == "Non-Sales":
175
  object_name = "UNBILLING_DATA__c"
176
  field_name = "TotalQuantity__c"
 
 
 
 
 
 
 
 
 
 
177
  elif mode == "Exit":
178
  if entry_type == "Sales":
179
  object_name = "Inventory_Management__c"
 
182
  object_name = "Un_Billable__c"
183
  field_name = "Sold_Out__c"
184
 
185
+ if not object_name or not field_name:
186
+ return "Invalid mode or entry type."
187
+
188
+ # Get valid fields for the specified Salesforce object
189
+ sf_object = sf.__getattr__(object_name)
190
+ schema = sf_object.describe()
191
+ valid_fields = {field["name"] for field in schema["fields"]}
192
 
193
+ # Extract product name and attributes
194
+ product_name = match_product_name(extracted_text)
195
+ attributes = extract_attributes(extracted_text)
196
+ model_name = attributes.get("Model Name", "").strip()
197
+
198
+ if not product_name:
199
+ return "Product name could not be matched from the extracted text."
200
+
201
+ attributes["Product name"] = product_name
202
+
203
+ # Handling "Exit" Mode (Updating Records)
204
+ if mode == "Exit":
205
+ # Query should only match exact product name or exact model name
206
+ query_conditions = []
207
+ if model_name:
208
+ query_conditions.append(f"{model_field_name} = '{model_name}'")
209
+ query_conditions.append(f"{product_field_name} = '{product_name}'")
210
+
211
+ query = f"SELECT Id, {field_name} FROM {object_name} WHERE {' OR '.join(query_conditions)} LIMIT 1"
212
  response = sf.query(query)
213
 
214
  if response["records"]:
215
  record_id = response["records"][0]["Id"]
216
+ updated_quantity = quantity # Overwrite the quantity
217
+ sf_object.update(record_id, {field_name: updated_quantity})
218
+ return f"✅ Updated record for product '{product_name}' ({model_name}) in {object_name}. New {field_name}: {updated_quantity}."
219
  else:
220
+ return f"❌ No matching record found for product '{product_name}' ({model_name}) in {object_name}."
221
+
222
+ # Handling "Entry" Mode (Creating Records)
223
+ else:
224
+ filtered_attributes = filter_valid_attributes(attributes, valid_fields)
225
+ filtered_attributes[field_name] = quantity
226
+ sf_object.create(filtered_attributes)
227
+ return f"✅ Data successfully exported to Salesforce object {object_name}."
228
 
229
  except Exception as e:
230
  return f"❌ Error interacting with Salesforce: {str(e)}"
231
+ # Function to pull structured data from Salesforce and display as a table
232
+ def pull_data_from_salesforce():
233
+ try:
234
+ sf = Salesforce(
 
235
  username=SALESFORCE_USERNAME,
236
  password=SALESFORCE_PASSWORD,
237
  security_token=SALESFORCE_SECURITY_TOKEN
238
  )
239
+
240
+ query = "SELECT Product_Name__c, Modal_Name__c, Current_Stocks__c FROM Inventory_Management__c LIMIT 100"
241
+ response = sf.query_all(query)
242
+
243
+ records = response.get("records", [])
244
+ if not records:
245
+ return "No data found in Salesforce.", None, None, None
246
+
247
+ df = pd.DataFrame(records)
248
+ df = df.drop(columns=['attributes'], errors='ignore')
249
 
250
  # Rename columns for better readability
251
+ df.rename(columns={
252
+ "Product_Name__c": "Product Name",
253
+ "Modal_Name__c": "Model Name",
254
+ "Current_Stocks__c": "Current Stocks"
255
+ }, inplace=True)
256
+
257
+ excel_path = "salesforce_data.xlsx"
258
+ df.to_excel(excel_path, index=False)
259
+
260
+ # Generate interactive vertical bar graph using Matplotlib
261
+ fig, ax = plt.subplots(figsize=(12, 8))
262
+ df.plot(kind='bar', x="Product Name", y="Current Stocks", ax=ax, legend=False)
263
+ ax.set_title("Stock Distribution by Product Name")
264
+ ax.set_xlabel("Product Name")
265
+ ax.set_ylabel("Current Stocks")
266
+ plt.xticks(rotation=45, ha="right", fontsize=10)
267
+ plt.tight_layout()
268
+ buffer = BytesIO()
269
+ plt.savefig(buffer, format="png")
270
+ buffer.seek(0)
271
+ img = Image.open(buffer)
272
+
273
+ return "Data successfully retrieved.", df, excel_path, img
274
+ except Exception as e:
275
+ return f"Error fetching data: {str(e)}", None, None, None
276
 
277
  # Unified function to handle image processing and Salesforce interaction
278
  def process_image(image, mode, entry_type, quantity):