gopichandra commited on
Commit
9829b2b
Β·
verified Β·
1 Parent(s): 44340d5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -80
app.py CHANGED
@@ -145,11 +145,13 @@ 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
- #πŸ“Š Function to interact with Salesforce based on mode and type
 
 
153
  def interact_with_salesforce(mode, entry_type, quantity, extracted_text):
154
  try:
155
  sf = Salesforce(
@@ -162,7 +164,6 @@ def interact_with_salesforce(mode, entry_type, quantity, extracted_text):
162
  object_name = None
163
  field_name = None
164
  product_field_name = "Product_Name__c"
165
- model_field_name = "Modal_Name__c" # Correct field for model name
166
 
167
  if mode == "Entry":
168
  if entry_type == "Sales":
@@ -182,97 +183,85 @@ def interact_with_salesforce(mode, entry_type, quantity, extracted_text):
182
  if not object_name or not field_name:
183
  return "Invalid mode or entry type."
184
 
185
- # Get valid fields for the specified Salesforce object
186
- sf_object = sf.__getattr__(object_name)
187
- schema = sf_object.describe()
188
- valid_fields = {field["name"] for field in schema["fields"]}
189
-
190
- # Extract product name and attributes
191
  product_name = match_product_name(extracted_text)
192
- attributes = extract_attributes(extracted_text)
193
- model_name = attributes.get("Model Name", "").strip()
194
-
195
  if not product_name:
196
  return "Product name could not be matched from the extracted text."
197
 
198
- attributes["Product name"] = product_name
199
-
200
  # Handling "Exit" Mode (Updating Records)
201
- Extract product name from the OCR text
202
- product_name = match_product_name(extracted_text)
203
- if not product_name:
204
- return "❌ Product name could not be matched from the extracted text."
205
-
206
- # Query Salesforce for the product record
207
- query = f"SELECT Id, {field_name} FROM {object_name} WHERE Product_Name__c = '{product_name}' LIMIT 1"
208
- response = sf.query(query)
 
 
 
209
 
210
- if response["records"]:
211
- record_id = response["records"][0]["Id"]
212
-
213
- # Update the quantity sold
214
- sf.__getattr__(object_name).update(record_id, {field_name: quantity})
215
- return f"βœ… Updated {field_name} for '{product_name}' in {object_name}. New Quantity: {quantity}."
216
- else:
217
- return f"❌ No record found for product '{product_name}' in {object_name}."
 
 
 
 
218
 
219
  except Exception as e:
220
- return f"❌ Salesforce Error: {str(e)}"
221
 
222
-
223
- # Handling "Entry" Mode (Creating Records)
224
- else:
225
- filtered_attributes = filter_valid_attributes(attributes, valid_fields)
226
- filtered_attributes[field_name] = quantity
227
- sf_object.create(filtered_attributes)
228
- return f"βœ… Data successfully exported to Salesforce object {object_name}."
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):
@@ -324,4 +313,5 @@ def app():
324
  ], ["πŸ“₯ OCR Processing", "πŸ“Š Salesforce Data Export"])
325
 
326
  if __name__ == "__main__":
327
- app().launch(share=True)
 
 
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
  def interact_with_salesforce(mode, entry_type, quantity, extracted_text):
156
  try:
157
  sf = Salesforce(
 
164
  object_name = None
165
  field_name = None
166
  product_field_name = "Product_Name__c"
 
167
 
168
  if mode == "Entry":
169
  if entry_type == "Sales":
 
183
  if not object_name or not field_name:
184
  return "Invalid mode or entry type."
185
 
186
+ # Extract product name
 
 
 
 
 
187
  product_name = match_product_name(extracted_text)
 
 
 
188
  if not product_name:
189
  return "Product name could not be matched from the extracted text."
190
 
 
 
191
  # Handling "Exit" Mode (Updating Records)
192
+ if mode == "Exit":
193
+ query = f"SELECT Id, {field_name} FROM {object_name} WHERE {product_field_name} = '{product_name}' LIMIT 1"
194
+ response = sf.query(query)
195
+
196
+ if response["records"]:
197
+ record_id = response["records"][0]["Id"]
198
+ updated_quantity = quantity
199
+ sf.__getattr__(object_name).update(record_id, {field_name: updated_quantity})
200
+ return f"βœ… Updated record for product '{product_name}' in {object_name}. New {field_name}: {updated_quantity}."
201
+ else:
202
+ return f"❌ No matching record found for product '{product_name}' in {object_name}."
203
 
204
+ # Handling "Entry" Mode (Creating Records)
205
+ try:
206
+ attributes = {
207
+ "Productname__c": product_name, # Mapping product name
208
+ field_name: quantity # Mapping quantity based on entry type
209
+ }
210
+ # Export data to Salesforce
211
+ sf.__getattr__(object_name).create(attributes)
212
+ return f"βœ… Data successfully exported to Salesforce object {object_name}."
213
+
214
+ except Exception as e:
215
+ return f"❌ Error interacting with Salesforce: {str(e)}"
216
 
217
  except Exception as e:
218
+ return f"❌ Error setting up Salesforce connection: {str(e)}"
219
 
220
+ # Function to pull structured data from Salesforce and display as a table
221
+ def pull_data_from_salesforce():
222
+ try:
223
+ sf = Salesforce(
 
 
 
 
 
 
 
 
 
224
  username=SALESFORCE_USERNAME,
225
  password=SALESFORCE_PASSWORD,
226
  security_token=SALESFORCE_SECURITY_TOKEN
227
  )
228
+
229
+ query = "SELECT Product_Name__c, Modal_Name__c, Current_Stocks__c FROM Inventory_Management__c LIMIT 100"
230
+ response = sf.query_all(query)
231
+
232
+ records = response.get("records", [])
233
+ if not records:
234
+ return "No data found in Salesforce.", None, None, None
235
+
236
+ df = pd.DataFrame(records)
237
+ df = df.drop(columns=['attributes'], errors='ignore')
238
 
239
  # Rename columns for better readability
240
+ df.rename(columns={
241
+ "Product_Name__c": "Product Name",
242
+ "Modal_Name__c": "Model Name",
243
+ "Current_Stocks__c": "Current Stocks"
244
+ }, inplace=True)
245
+
246
+ excel_path = "salesforce_data.xlsx"
247
+ df.to_excel(excel_path, index=False)
248
+
249
+ # Generate interactive vertical bar graph using Matplotlib
250
+ fig, ax = plt.subplots(figsize=(12, 8))
251
+ df.plot(kind='bar', x="Product Name", y="Current Stocks", ax=ax, legend=False)
252
+ ax.set_title("Stock Distribution by Product Name")
253
+ ax.set_xlabel("Product Name")
254
+ ax.set_ylabel("Current Stocks")
255
+ plt.xticks(rotation=45, ha="right", fontsize=10)
256
+ plt.tight_layout()
257
+ buffer = BytesIO()
258
+ plt.savefig(buffer, format="png")
259
+ buffer.seek(0)
260
+ img = Image.open(buffer)
261
+
262
+ return "Data successfully retrieved.", df, excel_path, img
263
+ except Exception as e:
264
+ return f"Error fetching data: {str(e)}", None, None, None
265
 
266
  # Unified function to handle image processing and Salesforce interaction
267
  def process_image(image, mode, entry_type, quantity):
 
313
  ], ["πŸ“₯ OCR Processing", "πŸ“Š Salesforce Data Export"])
314
 
315
  if __name__ == "__main__":
316
+ app().launch(share=True)
317
+