LogicGoInfotechSpaces commited on
Commit
6429b44
·
verified ·
1 Parent(s): 6dc1d39

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +583 -1
app.py CHANGED
@@ -53,7 +53,8 @@ os.makedirs("static", exist_ok=True)
53
  app.mount("/static", StaticFiles(directory="static"), name="static")
54
 
55
  # MongoDB connections and config
56
- DEFAULT_CATEGORY_FALLBACK = "69368f2f2e46bd68ae188963"
 
57
 
58
  primary_mongo_uri = os.getenv("MONGODB_URI") or os.getenv("MONGO_URI")
59
  primary_db_name = os.getenv("MONGODB_DB_NAME", "BG_DB")
@@ -576,3 +577,584 @@ def download(filename: str):
576
  if not os.path.exists(file_path):
577
  raise HTTPException(status_code=404, detail="File not found")
578
  return FileResponse(file_path, media_type="image/png", filename=filename)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  app.mount("/static", StaticFiles(directory="static"), name="static")
54
 
55
  # MongoDB connections and config
56
+ # Use an ObjectId for the default category so it is stored consistently
57
+ DEFAULT_CATEGORY_FALLBACK = ObjectId("69368f2f2e46bd68ae188963")
58
 
59
  primary_mongo_uri = os.getenv("MONGODB_URI") or os.getenv("MONGO_URI")
60
  primary_db_name = os.getenv("MONGODB_DB_NAME", "BG_DB")
 
577
  if not os.path.exists(file_path):
578
  raise HTTPException(status_code=404, detail="File not found")
579
  return FileResponse(file_path, media_type="image/png", filename=filename)
580
+
581
+
582
+
583
+ # import hashlib
584
+ # import logging
585
+ # import os
586
+ # import time
587
+ # import uuid
588
+ # from datetime import datetime, timedelta
589
+
590
+ # from bson import ObjectId
591
+ # from fastapi import FastAPI, File, Form, Header, HTTPException, UploadFile
592
+ # from fastapi.responses import FileResponse
593
+ # from fastapi.staticfiles import StaticFiles
594
+ # from gradio_client import Client, handle_file
595
+ # from pymongo import MongoClient
596
+ # from dotenv import load_dotenv
597
+
598
+ # # Load environment variables
599
+ # load_dotenv()
600
+
601
+ # logging.basicConfig(level=logging.INFO)
602
+ # logger = logging.getLogger("app")
603
+
604
+ # # Initialize FastAPI
605
+ # app = FastAPI()
606
+
607
+ # # Initialize Hugging Face Client (background remover Space) - lazy initialization
608
+ # client = None
609
+
610
+ # def get_client():
611
+ # """Lazy initialization of Gradio Client with timeout handling"""
612
+ # global client
613
+ # if client is None:
614
+ # max_retries = 3
615
+ # retry_delay = 2 # seconds
616
+
617
+ # for attempt in range(max_retries):
618
+ # try:
619
+ # # Initialize Gradio Client
620
+ # client = Client("LogicGoInfotechSpaces/background-remover")
621
+ # print(f"Gradio Client initialized successfully (attempt {attempt + 1})")
622
+ # break
623
+ # except Exception as e:
624
+ # if attempt < max_retries - 1:
625
+ # print(f"Error initializing Gradio Client (attempt {attempt + 1}/{max_retries}): {e}")
626
+ # print(f"Retrying in {retry_delay} seconds...")
627
+ # time.sleep(retry_delay)
628
+ # else:
629
+ # print(f"Failed to initialize Gradio Client after {max_retries} attempts: {e}")
630
+ # raise
631
+ # return client
632
+
633
+ # # Create static folder to store files
634
+ # os.makedirs("static", exist_ok=True)
635
+ # app.mount("/static", StaticFiles(directory="static"), name="static")
636
+
637
+ # # MongoDB connections and config
638
+ # DEFAULT_CATEGORY_FALLBACK = "69368f2f2e46bd68ae188963"
639
+
640
+ # primary_mongo_uri = os.getenv("MONGODB_URI") or os.getenv("MONGO_URI")
641
+ # primary_db_name = os.getenv("MONGODB_DB_NAME", "BG_DB")
642
+ # admin_mongo_uri = os.getenv("MONGODB_ADMIN") or os.getenv("MONGO_URI_ADMIN")
643
+ # admin_db_name = os.getenv("MONGODB_ADMIN_DB_NAME", "adminPanel")
644
+
645
+ # mongo_client = None
646
+ # mongo_collection = None
647
+ # admin_client = None
648
+ # media_clicks_collection = None
649
+
650
+ # if primary_mongo_uri:
651
+ # try:
652
+ # mongo_client = MongoClient(primary_mongo_uri)
653
+ # db = mongo_client.get_database(primary_db_name)
654
+ # mongo_collection = db["bgremove_logs"]
655
+ # except Exception as e:
656
+ # logger.error("MongoDB (primary) connection error: %s", e)
657
+
658
+ # if admin_mongo_uri:
659
+ # try:
660
+ # admin_client = MongoClient(admin_mongo_uri)
661
+ # admin_db = admin_client.get_database(admin_db_name)
662
+ # media_clicks_collection = admin_db["media_clicks"]
663
+ # logger.info("Admin DB in use: %s", admin_db_name)
664
+ # except Exception as e:
665
+ # logger.error("MongoDB (admin) connection error: %s", e)
666
+
667
+
668
+ # def _hash_to_object_id(value: str) -> ObjectId:
669
+ # digest = hashlib.sha1(value.encode("utf-8")).hexdigest()[:24]
670
+ # return ObjectId(digest)
671
+
672
+
673
+ # def normalize_user_id(raw_user_id):
674
+ # """Accepts ObjectId string, numeric string/int, or missing -> returns ObjectId."""
675
+ # if raw_user_id is None:
676
+ # return ObjectId(), "generated"
677
+
678
+ # value = str(raw_user_id).strip()
679
+ # if value == "":
680
+ # return ObjectId(), "generated_empty"
681
+
682
+ # try:
683
+ # return ObjectId(value), "parsed_objectid"
684
+ # except Exception:
685
+ # pass
686
+
687
+ # if value.isdigit():
688
+ # return _hash_to_object_id(value), "numeric_hashed"
689
+
690
+ # return _hash_to_object_id(value), "hashed"
691
+
692
+
693
+ # def normalize_category_id(raw_category_id):
694
+ # if raw_category_id is None:
695
+ # return DEFAULT_CATEGORY_FALLBACK, "default_missing"
696
+
697
+ # value = str(raw_category_id).strip()
698
+ # if value == "":
699
+ # return DEFAULT_CATEGORY_FALLBACK, "default_empty"
700
+
701
+ # return value, "provided"
702
+
703
+ # ##-------NEW CATEGORY CLICK-------#####
704
+ # def log_media_click(raw_user_id, raw_category_id):
705
+ # if media_clicks_collection is None:
706
+ # logger.info("Admin DB unavailable, skipping media click log")
707
+ # return
708
+
709
+ # user_oid, _ = normalize_user_id(raw_user_id)
710
+ # category_id, _ = normalize_category_id(raw_category_id)
711
+ # now = datetime.utcnow()
712
+
713
+ # # Normalize today to UTC midnight
714
+ # today_date = datetime(now.year, now.month, now.day)
715
+
716
+ # try:
717
+ # # --------------------------------------------------
718
+ # # STEP 1: ENSURE USER DOC EXISTS
719
+ # # --------------------------------------------------
720
+ # media_clicks_collection.update_one(
721
+ # {"userId": user_oid},
722
+ # {
723
+ # "$setOnInsert": {
724
+ # "userId": user_oid,
725
+ # "createdAt": now,
726
+ # "ai_edit_complete": 0,
727
+ # "ai_edit_daily_count": []
728
+ # },
729
+ # "$set": {
730
+ # "ai_edit_last_date": now,
731
+ # "updatedAt": now
732
+ # }
733
+ # },
734
+ # upsert=True
735
+ # )
736
+
737
+ # # --------------------------------------------------
738
+ # # STEP 2: DAILY COUNT (STRICT, UNIQUE, ORDERED)
739
+ # # --------------------------------------------------
740
+ # doc = media_clicks_collection.find_one(
741
+ # {"userId": user_oid},
742
+ # {"ai_edit_daily_count": 1}
743
+ # )
744
+
745
+ # daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
746
+
747
+ # # Build UNIQUE date → count map
748
+ # daily_map = {
749
+ # entry["date"]: entry["count"]
750
+ # for entry in daily_entries
751
+ # }
752
+
753
+ # # Find last known date
754
+ # last_date = max(daily_map.keys()) if daily_map else today_date
755
+
756
+ # # Fill ALL missing days with count = 0
757
+ # next_day = last_date + timedelta(days=1)
758
+ # while next_day < today_date:
759
+ # daily_map.setdefault(next_day, 0)
760
+ # next_day += timedelta(days=1)
761
+
762
+ # # Mark today as used (binary)
763
+ # daily_map[today_date] = 1
764
+
765
+ # # Rebuild list: OLD → NEW
766
+ # final_daily_entries = [
767
+ # {"date": d, "count": daily_map[d]}
768
+ # for d in sorted(daily_map.keys())
769
+ # ]
770
+
771
+ # # Keep last 32 days only
772
+ # final_daily_entries = final_daily_entries[-32:]
773
+
774
+ # # Atomic replace (NO $push)
775
+ # media_clicks_collection.update_one(
776
+ # {"userId": user_oid},
777
+ # {
778
+ # "$set": {
779
+ # "ai_edit_daily_count": final_daily_entries,
780
+ # "updatedAt": now
781
+ # }
782
+ # }
783
+ # )
784
+
785
+ # # --------------------------------------------------
786
+ # # STEP 3: UPDATE EXISTING CATEGORY (DATES CAN REPEAT)
787
+ # # --------------------------------------------------
788
+ # update_existing = media_clicks_collection.update_one(
789
+ # {
790
+ # "userId": user_oid,
791
+ # "categories.categoryId": category_id,
792
+ # },
793
+ # {
794
+ # "$inc": {
795
+ # "categories.$.click_count": 1,
796
+ # "ai_edit_complete": 1,
797
+ # },
798
+ # "$set": {
799
+ # "categories.$.lastClickedAt": now,
800
+ # "ai_edit_last_date": now,
801
+ # "updatedAt": now,
802
+ # },
803
+ # },
804
+ # )
805
+
806
+ # if update_existing.matched_count > 0:
807
+ # return
808
+
809
+ # # --------------------------------------------------
810
+ # # STEP 4: PUSH NEW CATEGORY (ORDER = TIME)
811
+ # # --------------------------------------------------
812
+ # media_clicks_collection.update_one(
813
+ # {"userId": user_oid},
814
+ # {
815
+ # "$inc": {"ai_edit_complete": 1},
816
+ # "$set": {
817
+ # "ai_edit_last_date": now,
818
+ # "updatedAt": now,
819
+ # },
820
+ # "$push": {
821
+ # "categories": {
822
+ # "categoryId": category_id,
823
+ # "click_count": 1,
824
+ # "lastClickedAt": now,
825
+ # }
826
+ # },
827
+ # },
828
+ # upsert=True,
829
+ # )
830
+
831
+ # except Exception as exc:
832
+ # logger.error("Failed to log media click: %s", exc)
833
+
834
+ # # def log_media_click(raw_user_id, raw_category_id):
835
+ # # if media_clicks_collection is None:
836
+ # # logger.info("Admin DB unavailable, skipping media click log")
837
+ # # return
838
+
839
+ # # user_oid, _ = normalize_user_id(raw_user_id)
840
+ # # category_id, _ = normalize_category_id(raw_category_id)
841
+ # # now = datetime.utcnow()
842
+
843
+ # # # Normalize to UTC midnight
844
+ # # today_date = datetime(now.year, now.month, now.day)
845
+
846
+ # # try:
847
+ # # # --------------------------------------------------
848
+ # # # STEP 1: ENSURE USER DOC + DAILY FIELD
849
+ # # # --------------------------------------------------
850
+ # # media_clicks_collection.update_one(
851
+ # # {"userId": user_oid},
852
+ # # {
853
+ # # "$setOnInsert": {
854
+ # # "userId": user_oid,
855
+ # # "createdAt": now,
856
+ # # "ai_edit_complete": 0,
857
+ # # "ai_edit_daily_count": []
858
+ # # },
859
+ # # "$set": {
860
+ # # "ai_edit_last_date": now,
861
+ # # "updatedAt": now
862
+ # # }
863
+ # # },
864
+ # # upsert=True
865
+ # # )
866
+
867
+ # # # --------------------------------------------------
868
+ # # # STEP 2: DAILY COUNT LOGIC (FIXED)
869
+ # # # --------------------------------------------------
870
+ # # doc = media_clicks_collection.find_one(
871
+ # # {"userId": user_oid},
872
+ # # {"ai_edit_daily_count": 1}
873
+ # # )
874
+
875
+ # # daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
876
+ # # daily_updates = []
877
+
878
+ # # if not daily_entries:
879
+ # # # FIRST EVER USAGE → ONLY TODAY
880
+ # # daily_updates.append({"date": today_date, "count": 1})
881
+ # # else:
882
+ # # existing_dates = {entry["date"].date() for entry in daily_entries}
883
+ # # last_date = max(entry["date"] for entry in daily_entries)
884
+
885
+ # # # Fill skipped days between last_date and today-1
886
+ # # next_day = last_date + timedelta(days=1)
887
+ # # while next_day.date() < today_date.date():
888
+ # # if next_day.date() not in existing_dates:
889
+ # # daily_updates.append({"date": next_day, "count": 0})
890
+ # # next_day += timedelta(days=1)
891
+
892
+ # # # Add today if missing
893
+ # # if today_date.date() not in existing_dates:
894
+ # # daily_updates.append({"date": today_date, "count": 1})
895
+
896
+ # # # Push updates if any
897
+ # # if daily_updates:
898
+ # # media_clicks_collection.update_one(
899
+ # # {"userId": user_oid},
900
+ # # {"$push": {"ai_edit_daily_count": {"$each": daily_updates}}}
901
+ # # )
902
+
903
+ # # # Sort oldest → newest and trim to last 32 entries
904
+ # # doc = media_clicks_collection.find_one({"userId": user_oid}, {"ai_edit_daily_count": 1})
905
+ # # daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
906
+ # # daily_entries.sort(key=lambda x: x["date"])
907
+ # # if len(daily_entries) > 32:
908
+ # # daily_entries = daily_entries[-32:]
909
+ # # media_clicks_collection.update_one(
910
+ # # {"userId": user_oid},
911
+ # # {"$set": {"ai_edit_daily_count": daily_entries}}
912
+ # # )
913
+
914
+
915
+ # # # --------------------------------------------------
916
+ # # # STEP 3: TRY UPDATING EXISTING CATEGORY
917
+ # # # --------------------------------------------------
918
+ # # update_existing = media_clicks_collection.update_one(
919
+ # # {
920
+ # # "userId": user_oid,
921
+ # # "categories.categoryId": category_id,
922
+ # # },
923
+ # # {
924
+ # # "$inc": {
925
+ # # "categories.$.click_count": 1,
926
+ # # "ai_edit_complete": 1,
927
+ # # },
928
+ # # "$set": {
929
+ # # "categories.$.lastClickedAt": now,
930
+ # # "ai_edit_last_date": now,
931
+ # # "updatedAt": now,
932
+ # # },
933
+ # # },
934
+ # # )
935
+
936
+ # # if update_existing.matched_count > 0:
937
+ # # return
938
+
939
+ # # # --------------------------------------------------
940
+ # # # STEP 4: PUSH NEW CATEGORY
941
+ # # # --------------------------------------------------
942
+ # # media_clicks_collection.update_one(
943
+ # # {"userId": user_oid},
944
+ # # {
945
+ # # "$inc": {
946
+ # # "ai_edit_complete": 1,
947
+ # # },
948
+ # # "$set": {
949
+ # # "ai_edit_last_date": now,
950
+ # # "updatedAt": now,
951
+ # # },
952
+ # # "$push": {
953
+ # # "categories": {
954
+ # # "categoryId": category_id,
955
+ # # "click_count": 1,
956
+ # # "lastClickedAt": now,
957
+ # # }
958
+ # # },
959
+ # # },
960
+ # # upsert=True,
961
+ # # )
962
+
963
+ # # except Exception as exc:
964
+ # # logger.error("Failed to log media click: %s", exc)
965
+
966
+ # # Health endpoint
967
+ # @app.get("/health")
968
+ # def health():
969
+ # return {"status": "ok"}
970
+
971
+ # # Upload source image
972
+ # @app.post("/source")
973
+ # async def upload_source(file: UploadFile = File(...)):
974
+ # file_id = str(uuid.uuid4()) + "_" + file.filename
975
+ # file_path = os.path.join("static", file_id)
976
+ # with open(file_path, "wb") as f:
977
+ # f.write(await file.read())
978
+ # return {"source_path": f"/static/{file_id}"}
979
+
980
+ # # Background remover (protected)
981
+ # @app.post("/bg-remove")
982
+ # async def bg_remove(
983
+ # file: UploadFile = File(...),
984
+ # authorization: str = Header(None),
985
+ # user_id: str = Form(None),
986
+ # category_id: str = Form(None),
987
+ # categoryId: str = Form(None),
988
+ # ):
989
+ # import time
990
+ # start_time = time.time() # start timer
991
+ # dt_now = datetime.utcnow() # UTC datetime
992
+
993
+ # # Token check
994
+ # if authorization != "Bearer logicgo@123":
995
+ # # Log fail
996
+ # if mongo_collection is not None:
997
+ # try:
998
+ # mongo_collection.insert_one({
999
+ # "status": "fail",
1000
+ # "ts": int(time.time()),
1001
+ # "datetime": dt_now,
1002
+ # "filename": file.filename,
1003
+ # "error": "Unauthorized",
1004
+ # "response_time_ms": 0
1005
+ # })
1006
+ # except Exception as e:
1007
+ # print("Mongo insert error:", e)
1008
+ # raise HTTPException(status_code=401, detail="Unauthorized")
1009
+
1010
+ # # Save uploaded file temporarily
1011
+ # file_id = str(uuid.uuid4()) + "_" + file.filename
1012
+ # input_path = os.path.join("static", file_id)
1013
+ # with open(input_path, "wb") as f:
1014
+ # f.write(await file.read())
1015
+
1016
+ # try:
1017
+ # # Call Hugging Face Space via gradio_client
1018
+ # hf_client = get_client()
1019
+ # result_path = hf_client.predict(
1020
+ # f=handle_file(input_path),
1021
+ # api_name="/png"
1022
+ # )
1023
+
1024
+ # # Ensure output has .png extension
1025
+ # output_id = f"bgremoved_{os.path.splitext(file_id)[0]}.png"
1026
+ # output_path = os.path.join("static", output_id)
1027
+ # os.replace(result_path, output_path)
1028
+
1029
+ # end_time = time.time()
1030
+ # response_time_ms = (end_time - start_time) * 1000 # in ms
1031
+
1032
+ # # Log success
1033
+ # if mongo_collection is not None:
1034
+ # try:
1035
+ # mongo_collection.insert_one({
1036
+ # "status": "success",
1037
+ # "ts": int(time.time()),
1038
+ # "datetime": dt_now,
1039
+ # "bg_removed_path": f"/static/{output_id}",
1040
+ # "filename": output_id,
1041
+ # "response_time_ms": response_time_ms
1042
+ # })
1043
+ # except Exception as e:
1044
+ # print("Mongo insert error:", e)
1045
+
1046
+ # log_media_click(
1047
+ # raw_user_id=user_id,
1048
+ # raw_category_id=category_id or categoryId,
1049
+ # )
1050
+
1051
+ # return {
1052
+ # "bg_removed_path": f"/static/{output_id}",
1053
+ # "filename": output_id,
1054
+ # "response_time_ms": response_time_ms
1055
+ # }
1056
+
1057
+ # except Exception as e:
1058
+ # # Remove temporary file if exists
1059
+ # if os.path.exists(input_path):
1060
+ # os.remove(input_path)
1061
+
1062
+ # end_time = time.time()
1063
+ # response_time_ms = (end_time - start_time) * 1000 # in ms
1064
+
1065
+ # # Log fail
1066
+ # if mongo_collection is not None:
1067
+ # try:
1068
+ # mongo_collection.insert_one({
1069
+ # "status": "fail",
1070
+ # "ts": int(time.time()),
1071
+ # "datetime": dt_now,
1072
+ # "filename": file.filename,
1073
+ # "error": str(e),
1074
+ # "response_time_ms": response_time_ms
1075
+ # })
1076
+ # except Exception as e2:
1077
+ # print("Mongo insert error:", e2)
1078
+
1079
+ # raise HTTPException(
1080
+ # status_code=503,
1081
+ # detail=f"Background removal service unavailable: {str(e)}"
1082
+ # )
1083
+
1084
+ # # @app.post("/bg-remove")
1085
+ # # async def bg_remove(
1086
+ # # file: UploadFile = File(...),
1087
+ # # authorization: str = Header(None)
1088
+ # # ):
1089
+ # # import time
1090
+ # # start_time = time.time() # start timer
1091
+
1092
+ # # # Token check
1093
+ # # if authorization != "Bearer logicgo@123":
1094
+ # # raise HTTPException(status_code=401, detail="Unauthorized")
1095
+
1096
+ # # # Save uploaded file temporarily
1097
+ # # file_id = str(uuid.uuid4()) + "_" + file.filename
1098
+ # # input_path = os.path.join("static", file_id)
1099
+ # # with open(input_path, "wb") as f:
1100
+ # # f.write(await file.read())
1101
+
1102
+ # # # Call Hugging Face Space via gradio_client (returns transparent PNG)
1103
+ # # try:
1104
+ # # hf_client = get_client()
1105
+ # # result_path = hf_client.predict(
1106
+ # # f=handle_file(input_path),
1107
+ # # api_name="/png"
1108
+ # # )
1109
+ # # except Exception as e:
1110
+ # # if os.path.exists(input_path):
1111
+ # # os.remove(input_path)
1112
+ # # raise HTTPException(
1113
+ # # status_code=503,
1114
+ # # detail=f"Background removal service unavailable: {str(e)}"
1115
+ # # )
1116
+
1117
+ # # # Ensure output has .png extension
1118
+ # # output_id = f"bgremoved_{os.path.splitext(file_id)[0]}.png"
1119
+ # # output_path = os.path.join("static", output_id)
1120
+
1121
+ # # # Move the transparent PNG to static folder
1122
+ # # os.replace(result_path, output_path)
1123
+
1124
+ # # # Calculate response time
1125
+ # # end_time = time.time()
1126
+ # # response_time_ms = (end_time - start_time) * 1000 # in milliseconds
1127
+
1128
+ # # # Log to MongoDB
1129
+ # # if mongo_collection is not None:
1130
+ # # try:
1131
+ # # mongo_collection.insert_one({
1132
+ # # "ts": int(time.time()),
1133
+ # # "bg_removed_path": f"/static/{output_id}",
1134
+ # # "filename": output_id,
1135
+ # # "response_time_ms": response_time_ms
1136
+ # # })
1137
+ # # except Exception as e:
1138
+ # # print("Mongo insert error:", e)
1139
+
1140
+ # # return {
1141
+ # # "bg_removed_path": f"/static/{output_id}",
1142
+ # # "filename": output_id,
1143
+ # # "response_time_ms": response_time_ms
1144
+ # # }
1145
+
1146
+ # # Preview processed image
1147
+ # @app.get("/preview/{filename}")
1148
+ # def preview(filename: str):
1149
+ # file_path = os.path.join("static", filename)
1150
+ # if not os.path.exists(file_path):
1151
+ # raise HTTPException(status_code=404, detail="File not found")
1152
+ # return FileResponse(file_path, media_type="image/png")
1153
+
1154
+ # # Download processed image
1155
+ # @app.get("/download/{filename}")
1156
+ # def download(filename: str):
1157
+ # file_path = os.path.join("static", filename)
1158
+ # if not os.path.exists(file_path):
1159
+ # raise HTTPException(status_code=404, detail="File not found")
1160
+ # return FileResponse(file_path, media_type="image/png", filename=filename)