Spaces:
Sleeping
Sleeping
Commit Β·
54fe70d
1
Parent(s): a3dd63c
cloudinary upload
Browse filesFiles changed (20)
- .env+4-1
- app/__pycache__/config.cpython-311.pyc
- app/__pycache__/main.cpython-311.pyc
- app/config.py+6
- app/main.py+25
- app/routers/__pycache__/incidents.cpython-311.pyc
- app/routers/incidents.py+10-1
- app/services/fallback_storage.py+61
- app/services/incidents.py+54-36
- app/uploads/222544d2e2e44e8d812becab341d74ef.txtAdded+1
- app/uploads/becb6a146b764fd6a50cb2b1305ccba6.jpgAdded
- create_test_user.pyAdded+44
- debug_cloudinary.pyAdded+66
- list_incidents.pyAdded+78
- test_api_cloudinary.pyAdded+118
- test_cloudinary.pyAdded+52
- test_cloudinary_improved.pyAdded+157
- test_cloudinary_mandatory.pyAdded+162
- test_files/cloudinary_test_7574.jpgAdded
- test_image.txtAdded+1
123JWT_SECRET_KEY=change_this_secret_in_productionMONGODB_URI=mongodb+srv://deepdblm_db_user:IqLKnKhwLLSOP1Ka@cluster0.0u1vpow.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0ALLOWED_ORIGINS=http://localhost:8080,https://marine-pollution-detection.vercel.app123456JWT_SECRET_KEY=change_this_secret_in_productionMONGODB_URI=mongodb+srv://deepdblm_db_user:IqLKnKhwLLSOP1Ka@cluster0.0u1vpow.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0ALLOWED_ORIGINS=http://localhost:8080,https://marine-pollution-detection.vercel.appCLOUDINARY_CLOUD_NAME=dler9jdjfCLOUDINARY_API_KEY=414766445792264CLOUDINARY_API_SECRET=kV133xtcDbxh4tEMvk5CS4WFx1U
1234567 unmodified lines141516171819from functools import lru_cachefrom typing import List, Unionimport osfrom pydantic_settings import BaseSettings7 unmodified linesaccess_token_expire_minutes: int = 60 * 24allowed_origins: Union[str, List[str]] = "http://localhost:5173"# Hugging Face Spaces specific settingsspace_id: str = os.getenv("SPACE_ID", "")12345677 unmodified lines1516171819202122232425from functools import lru_cachefrom typing import List, Unionimport osimport cloudinaryfrom pydantic_settings import BaseSettings7 unmodified linesaccess_token_expire_minutes: int = 60 * 24allowed_origins: Union[str, List[str]] = "http://localhost:5173"# Cloudinary settingscloudinary_cloud_name: strcloudinary_api_key: strcloudinary_api_secret: str# Hugging Face Spaces specific settingsspace_id: str = os.getenv("SPACE_ID", "")
123452 unmodified lines891011121321 unmodified lines353637383940import loggingfrom contextlib import asynccontextmanagerfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddleware2 unmodified linesfrom .database import get_collection, test_connectionfrom .routers import auth, incidentslogger = logging.getLogger(__name__)21 unmodified lines@asynccontextmanagerasync def lifespan(app: FastAPI):# Startupawait setup_database_indexes()yield# Shutdown (if needed in future)12345672 unmodified lines101112131415161718192021222321 unmodified lines454647484950515253545556575859606162636465import loggingfrom contextlib import asynccontextmanagerimport cloudinaryimport sysfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddleware2 unmodified linesfrom .database import get_collection, test_connectionfrom .routers import auth, incidents# Configure logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',handlers=[logging.StreamHandler(sys.stdout)])logger = logging.getLogger(__name__)21 unmodified lines@asynccontextmanagerasync def lifespan(app: FastAPI):# Startupsettings = get_settings()# Initialize Cloudinarytry:# Use environment variables from settingscloudinary.config(cloud_name=settings.cloudinary_cloud_name,api_key=settings.cloudinary_api_key,api_secret=settings.cloudinary_api_secret,secure=True)logger.info("Cloudinary initialized successfully with cloud name: %s", settings.cloudinary_cloud_name)except Exception as e:logger.error(f"Cloudinary initialization failed: {e}")await setup_database_indexes()yield# Shutdown (if needed in future)
44 unmodified lines4546474849505144 unmodified linesincident_class, severity = classification_resultconfidence_scores = Noneimage_path = await store_image(image)document = {"name": name,44 unmodified lines4546474849505152535455565758596044 unmodified linesincident_class, severity = classification_resultconfidence_scores = None# Upload image to Cloudinaryimage_path = Noneif image:image_path = await store_image(image)if not image_path:# If Cloudinary upload fails, raise an error since we're not using local fallbackraise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,detail="Failed to upload image to cloud storage")document = {"name": name,
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061"""Fallback storage service for when Cloudinary uploads fail.This provides a more controlled way to handle local storage fallback."""from pathlib import Pathfrom typing import Optionalimport loggingfrom uuid import uuid4logger = logging.getLogger(__name__)# Define fallback upload directoriesFALLBACK_PATHS = [Path(__file__).resolve().parent.parent / "uploads",Path("/tmp/uploads"),Path("/app/uploads")]# Find a usable directoryFALLBACK_DIR = Nonefor path in FALLBACK_PATHS:try:path.mkdir(exist_ok=True, parents=True)FALLBACK_DIR = pathlogger.info(f"Fallback storage directory ready: {FALLBACK_DIR}")breakexcept Exception as e:logger.warning(f"Cannot use {path} for fallback storage: {e}")continueif FALLBACK_DIR is None:logger.error("Could not create any fallback storage directory")FALLBACK_DIR = Path("/tmp") # Last resort fallbackasync def store_file_locally(file_content: bytes, original_filename: str) -> Optional[str]:"""Store a file in the local filesystem as a fallback when cloud storage failsArgs:file_content: The binary content of the fileoriginal_filename: The original filenameReturns:Relative path to the stored file or None if storage failed"""try:# Create a unique filenamefile_extension = Path(original_filename).suffixfilename = f"{uuid4().hex}{file_extension}"file_path = FALLBACK_DIR / filename# Write the filefile_path.write_bytes(file_content)logger.info(f"File saved to fallback storage: {file_path}")# Return a relative path that can be used in URLsreturn str(Path("uploads") / filename)except Exception as e:logger.error(f"Failed to save file to fallback storage: {e}")return None
1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383917 unmodified lines575859606162636465666768697071721 unmodified linefrom typing import Optionalfrom uuid import uuid4import loggingfrom ..database import get_collectionlogger = logging.getLogger(__name__)INCIDENTS_COLLECTION = "incidents"# Try multiple upload directory locationsupload_paths = [Path(__file__).resolve().parent.parent / "uploads",Path("/tmp/uploads"),Path("/app/uploads")]UPLOAD_DIR = Nonefor path in upload_paths:try:path.mkdir(exist_ok=True, parents=True)UPLOAD_DIR = pathlogger.info(f"Upload directory ready: {UPLOAD_DIR}")breakexcept PermissionError:logger.warning(f"Cannot create upload directory at {path}")continueexcept Exception as e:logger.warning(f"Error creating upload directory at {path}: {e}")continueif UPLOAD_DIR is None:logger.error("Could not create any upload directory")UPLOAD_DIR = Path("/tmp") # Fallback to /tmpasync def save_incident_document(document: dict) -> dict:collection = get_collection(INCIDENTS_COLLECTION)17 unmodified linesasync def store_image(upload_file) -> Optional[str]:if upload_file is None:return NoneUPLOAD_DIR.mkdir(parents=True, exist_ok=True)file_extension = Path(upload_file.filename).suffixfilename = f"{uuid4().hex}{file_extension}"file_path = UPLOAD_DIR / filenamecontents = await upload_file.read()file_path.write_bytes(contents)await upload_file.close()return str(Path("uploads") / filename)1 unmodified line234567891011121314151617181917 unmodified lines3738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889901 unmodified linefrom typing import Optionalfrom uuid import uuid4import loggingimport cloudinaryimport cloudinary.uploaderimport tempfileimport osfrom ..database import get_collectionfrom ..config import get_settingslogger = logging.getLogger(__name__)INCIDENTS_COLLECTION = "incidents"async def save_incident_document(document: dict) -> dict:collection = get_collection(INCIDENTS_COLLECTION)17 unmodified linesasync def store_image(upload_file) -> Optional[str]:"""Store an uploaded image using Cloudinary only.No local fallback - if Cloudinary upload fails, the function will return None."""if upload_file is None:return Nonetemp_path = Nonetry:logger.info(f"Starting image upload to Cloudinary for file: {upload_file.filename}")# Read the file contentcontents = await upload_file.read()logger.info(f"Read {len(contents)} bytes from uploaded file")# Create a temporary file to use with Cloudinarywith tempfile.NamedTemporaryFile(delete=False, suffix=Path(upload_file.filename).suffix) as temp_file:temp_path = temp_file.nametemp_file.write(contents)logger.info(f"Wrote content to temporary file: {temp_path}")# Upload to Cloudinary - ensuring we use the right resource typelogger.info("Starting Cloudinary upload...")# Add resource_type=auto to handle different file types correctlyupload_result = cloudinary.uploader.upload(temp_path,folder="marine_guard_incidents",resource_type="auto")# Return the Cloudinary URLcloudinary_url = upload_result["secure_url"]logger.info(f"Cloudinary upload successful. URL: {cloudinary_url}")await upload_file.close()return cloudinary_urlexcept Exception as e:logger.error(f"Failed to upload image to Cloudinary: {e}", exc_info=True)if upload_file:await upload_file.close()return Nonefinally:# Always clean up the temporary fileif temp_path and os.path.exists(temp_path):try:os.unlink(temp_path)logger.info(f"Deleted temporary file: {temp_path}")except Exception as e:logger.error(f"Failed to delete temporary file: {e}")
1This is a test image file for the API1234567891011121314151617181920212223242526272829303132333435363738394041424344import requestsimport json
# API endpoint for user signupAPI_URL = "http://localhost:8000/api/auth/signup"
def create_test_user(): """Create a test user for API testing""" try: # Prepare the user data user_data = { "email": "testuser@example.com", "password": "Password123!", "display_name": "Test User", "organization": "Test Org", "role": "citizen" } # Make the API request print(f"Creating test user at {API_URL}") response = requests.post( API_URL, data=json.dumps(user_data), headers={"Content-Type": "application/json"} ) # Process the response if response.status_code == 200: result = response.json() print("User created successfully!") print(f"Token: {result.get('access_token')[:15]}...") print(f"User ID: {result.get('user', {}).get('id')}") return result else: print(f"API request failed with status code {response.status_code}") print(f"Response: {response.text}") return None except Exception as e: print(f"Error creating test user: {e}") return None
if __name__ == "__main__": print("Creating test user for Marine Guard API") create_test_user()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import osimport cloudinaryimport cloudinary.uploaderfrom dotenv import load_dotenvimport logging
# Configure logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
# Load environment variablesload_dotenv()
# Configure Cloudinarycloudinary.config( cloud_name=os.getenv("CLOUDINARY_CLOUD_NAME"), api_key=os.getenv("CLOUDINARY_API_KEY"), api_secret=os.getenv("CLOUDINARY_API_SECRET"), secure=True)
def test_cloudinary_config(): print("Cloudinary configuration:") print(f"Cloud name: {cloudinary.config().cloud_name}") print(f"API key: {cloudinary.config().api_key}") print(f"API secret: {'*' * len(cloudinary.config().api_secret) if cloudinary.config().api_secret else 'Not set'}")
def upload_test_image(): try: # Create a test file test_file_path = "cloudinary_test.txt" with open(test_file_path, "w") as f: f.write("Test content for Cloudinary upload") # Upload to Cloudinary print("Uploading test file to Cloudinary...") upload_result = cloudinary.uploader.upload( test_file_path, folder="marine_guard_test", resource_type="auto" # Let Cloudinary auto-detect the resource type ) print(f"Upload successful! URL: {upload_result.get('secure_url')}") print(f"Public ID: {upload_result.get('public_id')}") print(f"Resource type: {upload_result.get('resource_type')}") # Clean up the test file os.unlink(test_file_path) print(f"Deleted local test file: {test_file_path}") return upload_result except Exception as e: logger.error(f"Error uploading to Cloudinary: {e}", exc_info=True) if os.path.exists(test_file_path): os.unlink(test_file_path) return None
if __name__ == "__main__": print("Testing detailed Cloudinary configuration and upload") test_cloudinary_config() result = upload_test_image() if result: print("β
Cloudinary upload test PASSED") else: print("β Cloudinary upload test FAILED")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import requestsimport json
# API endpoint for incident listingAPI_URL = "http://localhost:8000/api/incidents/list"
def get_token(): """Get a JWT token by authenticating with the API""" try: login_url = "http://localhost:8000/api/auth/login" login_data = { "email": "testuser@example.com", "password": "Password123!" } response = requests.post(login_url, data=json.dumps(login_data), headers={"Content-Type": "application/json"}) if response.status_code == 200: token = response.json().get("access_token") print(f"Authentication successful.") return token else: print(f"Authentication failed with status code {response.status_code}") print(response.text) return None except Exception as e: print(f"Error getting token: {e}") return None
def list_incidents(): """List all incidents for the authenticated user""" token = get_token() if not token: print("No token available, cannot proceed") return try: print(f"Fetching incidents from {API_URL}") response = requests.get( API_URL, headers={"Authorization": f"Bearer {token}"} ) if response.status_code == 200: incidents = response.json().get("incidents", []) print(f"Found {len(incidents)} incidents") # Print details of each incident for i, incident in enumerate(incidents): print(f"\nIncident {i + 1}:") print(f" ID: {incident.get('id')}") print(f" Type: {incident.get('incident_class')}") print(f" Severity: {incident.get('severity')}") print(f" Created: {incident.get('created_at')}") # Check if image path is a Cloudinary URL image_path = incident.get('image_path') if image_path: if 'cloudinary.com' in image_path: print(f" Image: Cloudinary URL - {image_path}") else: print(f" Image: Local path - {image_path}") else: print(" No image attached") return incidents else: print(f"API request failed with status code {response.status_code}") print(f"Response: {response.text}") return None except Exception as e: print(f"Error listing incidents: {e}") return None
if __name__ == "__main__": print("Listing incidents from Marine Guard API") list_incidents()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118import osimport requestsimport jsonimport sysfrom pathlib import Pathfrom dotenv import load_dotenv
# Load environment variables from .env fileload_dotenv()
# API endpoint for incident classificationAPI_URL = "http://localhost:8000/api/incidents/classify"
# JWT token (replace with your actual token)JWT_TOKEN = "" # Set this to test with your token
def get_token(): """Get a JWT token by authenticating with the API""" try: login_url = "http://localhost:8000/api/auth/login" login_data = { "email": "testuser@example.com", # Using our newly created test user "password": "Password123!" # Using the password for the test user } response = requests.post(login_url, data=json.dumps(login_data), headers={"Content-Type": "application/json"}) if response.status_code == 200: token = response.json().get("access_token") print(f"Authentication successful. Token: {token[:15]}..." if token else "No token in response") return token else: print(f"Authentication failed with status code {response.status_code}") print(response.text) return None except Exception as e: print(f"Error getting token: {e}") return None
def create_test_image(): """Create a test image file""" # Check if we're in the right directory current_dir = Path.cwd() print(f"Current directory: {current_dir}") # Create a directory for test files if it doesn't exist test_dir = current_dir / "test_files" test_dir.mkdir(exist_ok=True) # Path to the test image file test_image_path = test_dir / "test_image.txt" # Write some content to the file with open(test_image_path, "w") as f: f.write("This is a test image file for the API") print(f"Created test file at {test_image_path}") return test_image_path
def test_report_incident_with_image(): """Test reporting an incident with an image""" # Create a test image image_path = create_test_image() # Get a token if not provided token = JWT_TOKEN or get_token() if not token: print("No token available, cannot proceed with test") return try: # Prepare the form data form_data = { "description": "Test incident with image upload to Cloudinary", "name": "Cloudinary Test", "latitude": "37.7749", "longitude": "-122.4194" } # Prepare the file with open(image_path, "rb") as image_file: files = {"image": ("test_image.txt", image_file, "text/plain")} # Make the API request print(f"Sending request to {API_URL}") response = requests.post( API_URL, data=form_data, files=files, headers={"Authorization": f"Bearer {token}"} ) # Process the response if response.status_code == 200: print("Incident report successful!") print(f"Response: {response.json()}") return response.json() else: print(f"API request failed with status code {response.status_code}") print(f"Response: {response.text}") return None except Exception as e: print(f"Error testing incident report API: {e}") return None finally: # Clean up test image try: if os.path.exists(image_path): os.remove(image_path) print(f"Removed test file: {image_path}") except Exception as e: print(f"Error cleaning up test file: {e}")
if __name__ == "__main__": print("Testing Marine Guard Incident API with Cloudinary Integration") test_report_incident_with_image()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152import osimport cloudinaryimport cloudinary.uploaderfrom dotenv import load_dotenv
# Load environment variables from .env fileload_dotenv()
# Configure Cloudinarycloudinary.config( cloud_name=os.getenv("CLOUDINARY_CLOUD_NAME"), api_key=os.getenv("CLOUDINARY_API_KEY"), api_secret=os.getenv("CLOUDINARY_API_SECRET"), secure=True)
def test_cloudinary_upload(): """Test Cloudinary upload functionality""" try: # Try to upload a simple text as a test # Create a simple test file test_file = "test_image.txt" with open(test_file, "w") as f: f.write("This is a test file for Cloudinary upload") # Upload to Cloudinary print("Uploading to Cloudinary...") result = cloudinary.uploader.upload( test_file, folder="marine_guard_test", public_id="test_upload" ) print(f"Upload successful! URL: {result['secure_url']}") print(f"Full result: {result}") # Clean up the test file os.remove(test_file) return True except Exception as e: print(f"Error testing Cloudinary upload: {e}") return False
if __name__ == "__main__": print("Testing Cloudinary configuration") print(f"Cloud name: {os.getenv('CLOUDINARY_CLOUD_NAME')}") print(f"API key: {os.getenv('CLOUDINARY_API_KEY')}") print(f"API secret: {os.getenv('CLOUDINARY_API_SECRET')[:3]}...") test_result = test_cloudinary_upload() print(f"Test {'successful' if test_result else 'failed'}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157import osimport requestsimport jsonfrom pathlib import Pathfrom dotenv import load_dotenvimport random
# Load environment variablesload_dotenv()
# API endpoint for incident classificationAPI_URL = "http://localhost:8000/api/incidents/classify"
def get_token(): """Get a JWT token by authenticating with the API""" try: login_url = "http://localhost:8000/api/auth/login" login_data = { "email": "testuser@example.com", "password": "Password123!" } response = requests.post(login_url, data=json.dumps(login_data), headers={"Content-Type": "application/json"}) if response.status_code == 200: token = response.json().get("access_token") print(f"Authentication successful. Token: {token[:15]}...") return token else: print(f"Authentication failed with status code {response.status_code}") print(response.text) return None except Exception as e: print(f"Error getting token: {e}") return None
def create_test_image(): """Create a test image file - we'll use a .jpg extension but with text content for testing""" # Create a directory for test files if it doesn't exist test_dir = Path("test_files") test_dir.mkdir(exist_ok=True) # Use a .jpg extension to make sure Cloudinary tries to process it properly test_image_path = test_dir / f"test_image_{random.randint(1000, 9999)}.jpg" # Write some content to the file with open(test_image_path, "w") as f: f.write("This is a fake image file for testing Cloudinary uploads") print(f"Created test file at {test_image_path}") return test_image_path
def report_incident_with_image(): """Report an incident with an image via the API""" # Create a test image image_path = create_test_image() # Get a token token = get_token() if not token: print("No token available, cannot proceed with test") return False try: # Prepare the form data form_data = { "description": "Testing Cloudinary integration with improved logging", "name": "Cloudinary Test", "latitude": "37.7749", "longitude": "-122.4194" } # Prepare the file with open(image_path, "rb") as image_file: files = {"image": (image_path.name, image_file, "image/jpeg")} # Make the API request print(f"Sending request to {API_URL}") response = requests.post( API_URL, data=form_data, files=files, headers={"Authorization": f"Bearer {token}"} ) # Process the response if response.status_code == 200: print("Incident report successful!") print(f"Response: {response.json()}") # Get the incident ID from the response incident_id = response.json().get("incident_id") print(f"Created incident with ID: {incident_id}") # Now check the incident details to see if Cloudinary URL was used if incident_id: return check_incident_image(token, incident_id) return True else: print(f"API request failed with status code {response.status_code}") print(f"Response: {response.text}") return False except Exception as e: print(f"Error testing incident report API: {e}") return False finally: # Clean up test image try: if image_path.exists(): image_path.unlink() print(f"Removed test file: {image_path}") except Exception as e: print(f"Error cleaning up test file: {e}")
def check_incident_image(token, incident_id): """Check if the incident has a Cloudinary image URL""" try: # Get the list of incidents list_url = "http://localhost:8000/api/incidents/list" print(f"Fetching incidents to check for Cloudinary URL...") response = requests.get( list_url, headers={"Authorization": f"Bearer {token}"} ) if response.status_code == 200: incidents = response.json().get("incidents", []) # Find our incident for incident in incidents: if incident.get("id") == incident_id: image_path = incident.get("image_path") print(f"Found incident. Image path: {image_path}") if image_path and "cloudinary.com" in image_path: print("β
SUCCESS: Image was uploaded to Cloudinary!") return True else: print("β FAILED: Image was not uploaded to Cloudinary") return False print(f"Couldn't find incident with ID: {incident_id}") return False else: print(f"Failed to fetch incidents list: {response.status_code}") print(response.text) return False except Exception as e: print(f"Error checking incident: {e}") return False
if __name__ == "__main__": print("Testing Marine Guard incident reporting with Cloudinary integration") success = report_incident_with_image() print(f"Test {'PASSED' if success else 'FAILED'}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162"""Test script for Cloudinary-only image storage in the Marine Guard API.This script ensures that:1. We can authenticate with the API2. We can upload an image which gets stored in Cloudinary3. We can retrieve the incident which contains the Cloudinary URL"""import osimport requestsimport jsonfrom pathlib import Pathimport randomimport timefrom dotenv import load_dotenv
# Load environment variablesload_dotenv()
# API endpoint for incident classificationAPI_URL = "http://localhost:8000/api/incidents/classify"API_LIST_URL = "http://localhost:8000/api/incidents/list"API_LOGIN_URL = "http://localhost:8000/api/auth/login"
def authenticate(): """Authenticate with the API and get a JWT token""" try: login_data = { "email": "testuser@example.com", "password": "Password123!" } print(f"Authenticating with the API at {API_LOGIN_URL}...") response = requests.post(API_LOGIN_URL, json=login_data) if response.status_code == 200: token = response.json().get("access_token") print("β
Authentication successful!") return token else: print(f"β Authentication failed with status code {response.status_code}") print(response.text) return None except Exception as e: print(f"β Error during authentication: {e}") return None
def create_test_file(): """Create a test file to upload""" test_dir = Path("test_files") test_dir.mkdir(exist_ok=True) # Use a .txt extension since we just need any file that Cloudinary can handle file_path = test_dir / f"cloudinary_test_{random.randint(1000, 9999)}.txt" # Write simple text content with open(file_path, "w") as f: f.write("This is a test file for Cloudinary upload in Marine Guard API") print(f"Created test file at: {file_path}") return file_path
def report_incident(): """Report an incident with an image via the API""" token = authenticate() if not token: print("Cannot proceed with test - authentication failed") return False # Create a test image file image_path = create_test_file() try: # Prepare the form data form_data = { "description": "Cloudinary-only storage test with JPG image", "name": "Cloudinary Storage Test", "latitude": "42.3601", "longitude": "-71.0589" } # Prepare the file for upload with open(image_path, "rb") as image_file: files = {"image": (image_path.name, image_file, "text/plain")} # Make the API request print(f"Reporting incident to {API_URL}...") response = requests.post( API_URL, data=form_data, files=files, headers={"Authorization": f"Bearer {token}"} ) # Check the response if response.status_code == 200: result = response.json() incident_id = result.get("incident_id") print(f"β
Incident reported successfully! ID: {incident_id}") # Verify that the image was uploaded to Cloudinary return verify_cloudinary_upload(token, incident_id) else: print(f"β Incident reporting failed with status code {response.status_code}") print(f"Error details: {response.text}") return False except Exception as e: print(f"β Error reporting incident: {e}") return False finally: # Clean up the test file if os.path.exists(image_path): os.unlink(image_path) print(f"Deleted test file: {image_path}")
def verify_cloudinary_upload(token, incident_id): """Verify that the incident has a Cloudinary URL for its image""" try: print(f"Fetching incident details to verify Cloudinary URL...") # Short delay to ensure the incident is saved in the database time.sleep(1) response = requests.get( API_LIST_URL, headers={"Authorization": f"Bearer {token}"} ) if response.status_code == 200: incidents = response.json().get("incidents", []) for incident in incidents: if incident.get("id") == incident_id: image_path = incident.get("image_path") if image_path and "cloudinary.com" in image_path: print(f"β
SUCCESS: Image was uploaded to Cloudinary!") print(f"Cloudinary URL: {image_path}") return True else: print(f"β FAILED: Image does not have a Cloudinary URL") print(f"Image path: {image_path}") return False print(f"β FAILED: Could not find incident with ID {incident_id}") return False else: print(f"β FAILED: Could not fetch incidents list. Status: {response.status_code}") print(response.text) return False except Exception as e: print(f"β Error verifying Cloudinary upload: {e}") return False
if __name__ == "__main__": print("=" * 60) print("MARINE GUARD API - CLOUDINARY-ONLY STORAGE TEST") print("=" * 60) success = report_incident() print("\nTEST SUMMARY") print("=" * 60) print(f"Cloudinary storage test: {'β
PASSED' if success else 'β FAILED'}") print("=" * 60)1This is a test file for Cloudinary upload.env+4-1
app/__pycache__/config.cpython-311.pyc
app/__pycache__/main.cpython-311.pyc
app/config.py+6
app/main.py+25
app/routers/__pycache__/incidents.cpython-311.pyc
app/routers/incidents.py+10-1
app/services/fallback_storage.py+61
app/services/incidents.py+54-36
app/uploads/222544d2e2e44e8d812becab341d74ef.txtAdded+1
app/uploads/becb6a146b764fd6a50cb2b1305ccba6.jpgAdded

create_test_user.pyAdded+44
debug_cloudinary.pyAdded+66
list_incidents.pyAdded+78
test_api_cloudinary.pyAdded+118
test_cloudinary.pyAdded+52
test_cloudinary_improved.pyAdded+157
test_cloudinary_mandatory.pyAdded+162
test_files/cloudinary_test_7574.jpgAdded

test_image.txtAdded+1