from fastapi import FastAPI, File, UploadFile, Form, HTTPException from io import BytesIO import pandas as pd from fastapi.responses import StreamingResponse from extract import extract_data_from_image from parsing import process_extracted_text import csv import json import math app = FastAPI() @app.post("/extract-diamonds/") async def extract_diamonds(file: UploadFile = File(...)): try: file_content = await file.read() extracted_text = extract_data_from_image(BytesIO(file_content)) processed_data = process_extracted_text(extracted_text) return {"diamonds": processed_data["Diamonds"]} except Exception as e: raise HTTPException(status_code=400, detail=str(e)) @app.post("/process-image/") async def process_image( file: UploadFile = File(...), finding_14kt: float = Form(...), finding_18kt: float = Form(...), finding_plt: float = Form(...), diamond_rates: str = Form(...), gold_markup_type: str = Form(...), gold_markup_value: float = Form(...), platinum_markup_type: str = Form(...), platinum_markup_value: float = Form(...), diamond_markup_type: str = Form(...), diamond_markup_value: float = Form(...), finding_markup_type: str = Form(...), finding_markup_value: float = Form(...) ): try: diamond_rates_dict = json.loads(diamond_rates) file_content = await file.read() extracted_text = extract_data_from_image(BytesIO(file_content)) processed_data = process_extracted_text(extracted_text) metal_data = processed_data["Metal Details"] diamonds = processed_data["Diamonds"] # Calculate initial diamond values diamond_values_sum = 0 for idx, diamond in enumerate(diamonds): rate = float(diamond_rates_dict.get(str(idx), 0)) diamond["Diamond Rate"] = rate diamond_weight = float(diamond.get("Diamond Weight", 0)) diamond_value = round(diamond_weight * rate, 2) diamond["Diamond Value"] = diamond_value diamond_values_sum += diamond_value # Apply markup to finding values - before updating metal_data if finding_markup_type == "percentage": finding_markup_factor = 1 + (finding_markup_value / 100) finding_14kt = round(finding_14kt * finding_markup_factor, 2) finding_18kt = round(finding_18kt * finding_markup_factor, 2) finding_plt = round(finding_plt * finding_markup_factor, 2) elif finding_markup_type == "fixed": finding_14kt = round(finding_14kt + finding_markup_value, 2) finding_18kt = round(finding_18kt + finding_markup_value, 2) finding_plt = round(finding_plt + finding_markup_value, 2) elif finding_markup_type == "times": finding_14kt = round(finding_14kt * finding_markup_value, 2) finding_18kt = round(finding_18kt * finding_markup_value, 2) finding_plt = round(finding_plt * finding_markup_value, 2) metal_data.update({ "Finding For Gold 14KT": finding_14kt, "Finding For Gold 18KT": finding_18kt, "Finding for Plt.": finding_plt, "Finding Markup Type": finding_markup_type, "Finding Markup Value": finding_markup_value, }) # Apply markup to gold values - only percentage or fixed if gold_markup_type == "percentage": gold_markup_factor = 1 + (gold_markup_value / 100) metal_data["Gold Value 14K"] = round(metal_data["Gold Value 14K"] * gold_markup_factor, 2) metal_data["Gold Value 18K"] = round(metal_data["Gold Value 18K"] * gold_markup_factor, 2) elif gold_markup_type == "fixed": # Ensure the markup value is properly applied metal_data["Gold Value 14K"] = round(metal_data["Gold Value 14K"] + gold_markup_value, 2) metal_data["Gold Value 18K"] = round(metal_data["Gold Value 18K"] + gold_markup_value, 2) elif gold_markup_type == "times": metal_data["Gold Value 14K"] = round(metal_data["Gold Value 14K"] * gold_markup_value, 2) metal_data["Gold Value 18K"] = round(metal_data["Gold Value 18K"] * gold_markup_value, 2) # Apply markup to platinum values - only percentage or fixed if platinum_markup_type == "percentage": platinum_markup_factor = 1 + (platinum_markup_value / 100) metal_data["Plat Value"] = round(metal_data["Plat Value"] * platinum_markup_factor, 2) elif platinum_markup_type == "fixed": # Ensure the markup value is properly applied metal_data["Plat Value"] = round(metal_data["Plat Value"] + platinum_markup_value, 2) elif platinum_markup_type == "times": metal_data["Plat Value"] = round(metal_data["Plat Value"] * platinum_markup_value, 2) # Apply markup to diamond values - only percentage or fixed if diamond_markup_type == "percentage": diamond_markup_factor = 1 + (diamond_markup_value / 100) for diamond in diamonds: diamond["Diamond Value"] = round(diamond["Diamond Value"] * diamond_markup_factor, 2) elif diamond_markup_type == "fixed": # Ensure the markup value is properly applied for each diamond for diamond in diamonds: diamond["Diamond Value"] = round(diamond["Diamond Value"] + diamond_markup_value, 2) elif diamond_markup_type == "times": for diamond in diamonds: diamond["Diamond Value"] = round(diamond["Diamond Value"] * diamond_markup_value, 2) # Recalculate diamond_values_sum after applying markup diamond_values_sum = sum(diamond["Diamond Value"] for diamond in diamonds) # Calculate prices with the marked-up values usd_14k = ( metal_data["Gold Value 14K"] + finding_14kt + diamond_values_sum + metal_data["Labour 14K"] + metal_data["Rhodium"] ) usd_14k = math.ceil(usd_14k) + 1 usd_18k = ( metal_data["Gold Value 18K"] + finding_18kt + diamond_values_sum + metal_data["Labour 18K"] + metal_data["Rhodium"] ) usd_18k = math.ceil(usd_18k) + 1 usd_pt = ( metal_data["Plat Value"] + finding_plt + diamond_values_sum + metal_data["Labour PT"] + metal_data["Rhodium"] ) usd_pt = math.ceil(usd_pt) + 1 gbp_14k = usd_14k * 0.78 gbp_18k = usd_18k * 0.78 gbp_pt = usd_pt * 0.78 duty_14k = gbp_14k * 1.025 duty_18k = gbp_18k * 1.025 duty_pt = gbp_pt * 1.025 freight = 75 landing_14k = duty_14k + freight landing_18k = duty_18k + freight landing_pt = duty_pt + freight # Add markup information to metal_data for reference metal_data.update({ "Gold Markup Type": gold_markup_type, "Gold Markup Value": gold_markup_value, "Platinum Markup Type": platinum_markup_type, "Platinum Markup Value": platinum_markup_value, "Diamond Markup Type": diamond_markup_type, "Diamond Markup Value": diamond_markup_value, "Price of USD 14K": f"$ {usd_14k:.2f}", "Price of USD 18K": f"$ {usd_18k:.2f}", "Price of USD PT": f"$ {usd_pt:.2f}", "Price of GBP 14K @ 1/0.78": f"£ {gbp_14k:.2f}", "Price of GBP 18K @ 1/0.78": f"£ {gbp_18k:.2f}", "Price of GBP PT @ 1/0.78": f"£ {gbp_pt:.2f}", "14K Duty @ 2.5% Including": f"£ {duty_14k:.2f}", "18K Duty @ 2.5% Including": f"£ {duty_18k:.2f}", "PT950 Duty @ 2.5% Including": f"£ {duty_pt:.2f}", "Freight": f"£ {freight:.2f}", "14K Landing Cost (Duty + Freight)": f"£ {landing_14k:.2f}", "18K Landing Cost (Duty + Freight)": f"£ {landing_18k:.2f}", "PT950 Landing Cost (Duty + Freight)": f"£ {landing_pt:.2f}" }) if not diamonds: final_df = pd.DataFrame([metal_data]) else: # Find the gold lock and platinum lock columns dynamically gold_lock_col = next((col for col in metal_data.keys() if "Gold Lock @" in col), None) platinum_lock_col = next((col for col in metal_data.keys() if "Platinum Lock" in col), None) # Make sure these columns are included in metal_columns metal_columns = [ "Customer Ref", gold_lock_col, # Include the gold lock column platinum_lock_col, # Include the platinum lock column "Wt. in gram 14K", "Wt. in gram 18K", "Wt. in gram PLT", "Gold Rate (including loss) 14KT", "Gold Rate (including loss) 18KT", "Plat rate (including Lab)", "Gold Value 14K", "Gold Value 18K", "Plat Value" ] finding_columns = [ "Finding For Gold 14KT", "Finding For Gold 18KT", "Finding for Plt.", "Rhodium", "Stamping" ] labour_columns = [ "Labour 14K", "Labour 18K", "Labour PT" ] price_columns = [ "Price of USD 14K", "Price of USD 18K", "Price of USD PT", "Price of GBP 14K @ 1/0.78", "Price of GBP 18K @ 1/0.78", "Price of GBP PT @ 1/0.78", "14K Duty @ 2.5% Including", "18K Duty @ 2.5% Including", "PT950 Duty @ 2.5% Including", "Freight", "14K Landing Cost (Duty + Freight)", "18K Landing Cost (Duty + Freight)", "PT950 Landing Cost (Duty + Freight)" ] # Filter out any None values from columns metal_columns = [col for col in metal_columns if col is not None] metal_data_basic = {k: v for k, v in metal_data.items() if k in metal_columns} findings_data = {k: v for k, v in metal_data.items() if k in finding_columns} labour_data = {k: v for k, v in metal_data.items() if k in labour_columns} price_data = {k: v for k, v in metal_data.items() if k in price_columns} metal_df = pd.DataFrame([metal_data_basic]) findings_df = pd.DataFrame([findings_data]) labour_df = pd.DataFrame([labour_data]) price_df = pd.DataFrame([price_data]) diamonds_df = pd.DataFrame(diamonds) empty_metal = pd.DataFrame([{k: '' for k in metal_columns}] * (len(diamonds_df) - 1)) empty_findings = pd.DataFrame([{k: '' for k in finding_columns}] * (len(diamonds_df) - 1)) empty_labour = pd.DataFrame([{k: '' for k in labour_columns}] * (len(diamonds_df) - 1)) empty_prices = pd.DataFrame([{k: '' for k in price_columns}] * (len(diamonds_df) - 1)) combined_metal = pd.concat([metal_df, empty_metal], ignore_index=True) combined_findings = pd.concat([findings_df, empty_findings], ignore_index=True) combined_labour = pd.concat([labour_df, empty_labour], ignore_index=True) combined_prices = pd.concat([price_df, empty_prices], ignore_index=True) final_df = pd.concat([ combined_metal, diamonds_df, combined_findings, combined_labour, combined_prices ], axis=1) for col in price_columns: if col in final_df.columns: # Check if column exists final_df[col] = final_df[col].astype(str) final_df[col] = final_df[col].apply(lambda x: x.strip('"').strip("'") if x else '') if "GBP" in col: final_df[col] = final_df[col].apply(lambda x: x.replace('£', '£') if x else '') output = BytesIO() final_df.to_csv( output, index=False, encoding='utf-8-sig', quoting=csv.QUOTE_MINIMAL, escapechar='\\' ) output.seek(0) return StreamingResponse( output, media_type="text/csv; charset=utf-8", headers={ "Content-Disposition": "attachment; filename=output.csv", "Content-Type": "text/csv; charset=utf-8" } ) except Exception as e: raise HTTPException(status_code=400, detail=str(e))