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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
try:
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
|
| 20 |
-
|
| 21 |
-
target_sizes = torch.tensor([image.size[::-1]]) # image size reversed to match model format
|
| 22 |
-
results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.5)[0]
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
|
| 31 |
-
|
| 32 |
-
return image, "Object detection complete."
|
| 33 |
|
| 34 |
except Exception as e:
|
| 35 |
-
return
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
)
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
from paddleocr import PaddleOCR
|
| 4 |
+
from PIL import Image, ImageEnhance
|
| 5 |
import gradio as gr
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import re
|
| 8 |
+
from simple_salesforce import Salesforce
|
| 9 |
+
|
| 10 |
+
# Attribute mappings: readable names to Salesforce API names
|
| 11 |
+
ATTRIBUTE_MAPPING = {
|
| 12 |
+
"Product name": "Productname__c",
|
| 13 |
+
"Colour": "Colour__c",
|
| 14 |
+
"Motortype": "Motortype__c",
|
| 15 |
+
"Frequency": "Frequency__c",
|
| 16 |
+
"Grossweight": "Grossweight__c",
|
| 17 |
+
"Ratio": "Ratio__c",
|
| 18 |
+
"MotorFrame": "Motorframe__c",
|
| 19 |
+
"Model": "Model__c",
|
| 20 |
+
"Speed": "Speed__c",
|
| 21 |
+
"Quantity": "Quantity__c",
|
| 22 |
+
"Voltage": "Voltage__c",
|
| 23 |
+
"Material": "Material__c",
|
| 24 |
+
"Type": "Type__c",
|
| 25 |
+
"Horsepower": "Horsepower__c",
|
| 26 |
+
"Consignee": "Consignee__c",
|
| 27 |
+
"LOT": "LOT__c",
|
| 28 |
+
"Stage": "Stage__c",
|
| 29 |
+
"Outlet": "Outlet__c",
|
| 30 |
+
"Serialnumber": "Serialnumber__c",
|
| 31 |
+
"HeadSize": "Headsize__c",
|
| 32 |
+
"Deliverysize": "Deliverysize__c",
|
| 33 |
+
"Phase": "Phase__c",
|
| 34 |
+
"Size": "Size__c",
|
| 35 |
+
"MRP": "MRP__c",
|
| 36 |
+
"Usebefore": "Usebefore__c",
|
| 37 |
+
"Height": "Height__c",
|
| 38 |
+
"MaximumDischarge Flow": "Maximumdischargeflow__c",
|
| 39 |
+
"DischargeRange": "Dischargeflow__c",
|
| 40 |
+
"Assembledby": "Manufacturer__c",
|
| 41 |
+
"Manufacturedate": "Manufacturedate__c",
|
| 42 |
+
"Companyname": "Companyname__c",
|
| 43 |
+
"Customercarenumber": "Customercarenumber__c",
|
| 44 |
+
"SellerAddress": "Selleraddress__c",
|
| 45 |
+
"Selleremail": "Selleremail__c",
|
| 46 |
+
"GSTIN": "GSTIN__c",
|
| 47 |
+
"Totalamount": "Totalamount__c",
|
| 48 |
+
"Paymentstatus": "Paymentstatus__c",
|
| 49 |
+
"Paymentmethod": "Paymentstatus__c",
|
| 50 |
+
"Invoicedate": "Manufacturedate__c",
|
| 51 |
+
"Warranty": "Warranty__c",
|
| 52 |
+
"Brand": "Brand__c",
|
| 53 |
+
"Motorhorsepower": "Motorhorsepower__c",
|
| 54 |
+
"Power": "Power__c",
|
| 55 |
+
"Motorphase": "Motorphase__c",
|
| 56 |
+
"Enginetype": "Enginetype__c",
|
| 57 |
+
"Tankcapacity": "Tankcapacity__c",
|
| 58 |
+
"Head": "Head__c",
|
| 59 |
+
"Usage/Application": "Usage_Application__c",
|
| 60 |
+
"Volts": "volts__c",
|
| 61 |
+
"Hertz": "Hertz__c",
|
| 62 |
+
"Frame": "frame__c",
|
| 63 |
+
"Mounting": "Mounting__c",
|
| 64 |
+
"Tollfreenumber": "Tollfreenumber__c",
|
| 65 |
+
"Pipesize": "Pipesize__c",
|
| 66 |
+
"Manufacturer": "Manufacturer__c",
|
| 67 |
+
"Office": "Office__c",
|
| 68 |
+
"SRnumber": "SRnumber__c",
|
| 69 |
+
"TypeOfEndUse": "TypeOfEndUse__c",
|
| 70 |
+
"Model Name": "Model_Name_Number__c",
|
| 71 |
+
"coolingmethod": "coolingmethod__c"
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
# Salesforce credentials
|
| 75 |
+
SALESFORCE_USERNAME = "venkatramana@sandbox.com"
|
| 76 |
+
SALESFORCE_PASSWORD = "Venkat12345@"
|
| 77 |
+
SALESFORCE_SECURITY_TOKEN = "GhcJJmjBEefdnukJoz4CAQlR"
|
| 78 |
+
|
| 79 |
+
# Initialize PaddleOCR
|
| 80 |
+
ocr = PaddleOCR(use_angle_cls=True, lang='en')
|
| 81 |
+
|
| 82 |
+
# Environment variable for the Excel file path
|
| 83 |
+
EXCEL_FILE_PATH = os.getenv("EXCEL_FILE_PATH", "DataStorage.xlsx")
|
| 84 |
+
|
| 85 |
+
# Function to extract text using PaddleOCR
|
| 86 |
+
def extract_text(image):
|
| 87 |
+
result = ocr.ocr(image)
|
| 88 |
+
extracted_text = []
|
| 89 |
+
for line in result[0]:
|
| 90 |
+
extracted_text.append(line[1][0])
|
| 91 |
+
return "\n".join(extracted_text)
|
| 92 |
+
|
| 93 |
+
# Function to find attributes and their values
|
| 94 |
+
def find_attributes(text):
|
| 95 |
+
structured_data = {}
|
| 96 |
+
for readable_attr, sf_attr in ATTRIBUTE_MAPPING.items():
|
| 97 |
+
pattern = rf"{re.escape(readable_attr)}[:\-]?\s*(.+)" # Match the attribute and capture its value
|
| 98 |
+
match = re.search(pattern, text, re.IGNORECASE)
|
| 99 |
+
if match:
|
| 100 |
+
structured_data[sf_attr] = match.group(1).strip()
|
| 101 |
+
return structured_data
|
| 102 |
+
|
| 103 |
+
# Function to sanitize numeric values
|
| 104 |
+
def sanitize_numeric(value):
|
| 105 |
+
try:
|
| 106 |
+
if isinstance(value, (int, float)):
|
| 107 |
+
return value
|
| 108 |
+
if '/' in value: # Handle fraction strings like "1/2"
|
| 109 |
+
numerator, denominator = value.split('/')
|
| 110 |
+
return float(numerator) / float(denominator)
|
| 111 |
+
sanitized = re.sub(r'[^\d\.\-]', '', value) # Remove non-numeric characters
|
| 112 |
+
return float(sanitized) if sanitized else None
|
| 113 |
+
except (ValueError, ZeroDivisionError):
|
| 114 |
+
return None
|
| 115 |
+
|
| 116 |
+
# Function to save structured data to the constant Excel file
|
| 117 |
+
def save_to_excel(data):
|
| 118 |
+
if not data:
|
| 119 |
+
return "No data to save."
|
| 120 |
+
|
| 121 |
+
if not os.path.exists(EXCEL_FILE_PATH):
|
| 122 |
+
df = pd.DataFrame([data])
|
| 123 |
+
df.to_excel(EXCEL_FILE_PATH, index=False, engine="openpyxl")
|
| 124 |
+
else:
|
| 125 |
+
existing_df = pd.read_excel(EXCEL_FILE_PATH, engine="openpyxl")
|
| 126 |
+
new_data_df = pd.DataFrame([data])
|
| 127 |
+
updated_df = pd.concat([existing_df, new_data_df], ignore_index=True)
|
| 128 |
+
updated_df.to_excel(EXCEL_FILE_PATH, index=False, engine="openpyxl")
|
| 129 |
+
|
| 130 |
+
return EXCEL_FILE_PATH
|
| 131 |
+
|
| 132 |
+
# Function to handle entry mode
|
| 133 |
+
def add_stock_to_venkataramana(data):
|
| 134 |
+
try:
|
| 135 |
+
sf = Salesforce(
|
| 136 |
+
username=SALESFORCE_USERNAME,
|
| 137 |
+
password=SALESFORCE_PASSWORD,
|
| 138 |
+
security_token=SALESFORCE_SECURITY_TOKEN,
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
object_name = "VENKATA_RAMANA_MOTORS__c"
|
| 142 |
+
sf_object = sf.__getattr__(object_name)
|
| 143 |
+
|
| 144 |
+
schema = sf_object.describe()
|
| 145 |
+
valid_fields = {field["name"] for field in schema["fields"]}
|
| 146 |
|
| 147 |
+
filtered_record = {k: v for k, v in data.items() if k in valid_fields and v is not None}
|
| 148 |
+
sf_object.create(filtered_record)
|
| 149 |
+
return f"Data successfully added to {object_name}."
|
| 150 |
+
except Exception as e:
|
| 151 |
+
return f"Error adding stock to VENKATA_RAMANA_MOTORS__c: {str(e)}"
|
| 152 |
+
|
| 153 |
+
# Function to handle exit mode
|
| 154 |
+
def subtract_stock_from_inventory(data):
|
| 155 |
+
try:
|
| 156 |
+
sf = Salesforce(
|
| 157 |
+
username=SALESFORCE_USERNAME,
|
| 158 |
+
password=SALESFORCE_PASSWORD,
|
| 159 |
+
security_token=SALESFORCE_SECURITY_TOKEN,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
object_name = "Inventory_Management__c"
|
| 163 |
+
sf_object = sf.__getattr__(object_name)
|
| 164 |
+
|
| 165 |
+
product_name = data.get("Productname__c")
|
| 166 |
+
quantity = data.get("Quantity__c", 0)
|
| 167 |
+
|
| 168 |
+
if not product_name:
|
| 169 |
+
return "Product name is missing in the data. Cannot update stock."
|
| 170 |
+
|
| 171 |
+
# Query existing stock record
|
| 172 |
+
query = f"SELECT Id, Quantity_Sold__c FROM {object_name} WHERE Product_Name__c = '{product_name}' LIMIT 1"
|
| 173 |
+
response = sf.query(query)
|
| 174 |
+
|
| 175 |
+
if not response["records"]:
|
| 176 |
+
return f"No stock found for product '{product_name}'. Cannot update stock."
|
| 177 |
|
| 178 |
+
record_id = response["records"][0]["Id"]
|
| 179 |
+
current_quantity_sold = response["records"][0].get("Quantity_Sold__c", 0)
|
| 180 |
+
|
| 181 |
+
# Update the quantity sold
|
| 182 |
+
updated_quantity_sold = current_quantity_sold + quantity
|
| 183 |
+
|
| 184 |
+
sf_object.update(record_id, {"Quantity_Sold__c": updated_quantity_sold})
|
| 185 |
+
|
| 186 |
+
return f"Stock updated successfully in exit mode. Quantity sold for product '{product_name}': {updated_quantity_sold}."
|
| 187 |
+
except Exception as e:
|
| 188 |
+
return f"Error updating stock in Inventory_Management__c: {str(e)}"
|
| 189 |
+
|
| 190 |
+
# Unified function for processing
|
| 191 |
+
def process_image(image, quantity, mode):
|
| 192 |
try:
|
| 193 |
+
extracted_text = extract_text(image)
|
| 194 |
+
attributes = find_attributes(extracted_text)
|
| 195 |
+
attributes["Quantity__c"] = sanitize_numeric(quantity)
|
| 196 |
+
|
| 197 |
+
if not attributes:
|
| 198 |
+
return "No attributes found in the image.", None
|
| 199 |
|
| 200 |
+
numbered_output = "\n".join(
|
| 201 |
+
[f"{key.replace('__c', '')}: {value}" for key, value in attributes.items()]
|
| 202 |
+
)
|
| 203 |
|
| 204 |
+
file_path = save_to_excel(attributes)
|
|
|
|
|
|
|
| 205 |
|
| 206 |
+
if mode == "Entry":
|
| 207 |
+
message = add_stock_to_venkataramana(attributes)
|
| 208 |
+
elif mode == "Exit":
|
| 209 |
+
message = subtract_stock_from_inventory(attributes)
|
| 210 |
+
else:
|
| 211 |
+
message = "Invalid mode. Please select Entry or Exit."
|
| 212 |
|
| 213 |
+
return f"{numbered_output}\n\n{message}", file_path
|
|
|
|
| 214 |
|
| 215 |
except Exception as e:
|
| 216 |
+
return f"Error during processing: {str(e)}", None
|
| 217 |
+
|
| 218 |
+
interface = gr.Interface(
|
| 219 |
+
fn=process_image,
|
| 220 |
+
inputs=[
|
| 221 |
+
gr.Image(type="numpy"),
|
| 222 |
+
gr.Number(label="Quantity", value=1, interactive=True),
|
| 223 |
+
gr.Dropdown(label="Mode", choices=["Entry", "Exit"], value="Entry")
|
| 224 |
+
],
|
| 225 |
+
outputs=[
|
| 226 |
+
gr.Text(label="Image Data Viewer"),
|
| 227 |
+
gr.File(label="Data Storage Manager")
|
| 228 |
+
],
|
| 229 |
+
title="Processing - VENKATARAMANA MOTORS",
|
| 230 |
+
description="Process images to update stock in Salesforce and save to Excel.",
|
| 231 |
)
|
| 232 |
|
| 233 |
+
if __name__ == "__main__":
|
| 234 |
+
interface.launch(share=True)
|
| 235 |
+
|