Spaces:
Runtime error
Runtime error
Download utils.py from NexNoor/PoultryShieldAI: direct link, hf CLI and curl.
- Browser
- Download file 4.4 kB
-
https://huggingface.co/spaces/NexNoor/PoultryShieldAI/resolve/main/utils.py
- Command line
-
hf download hf://spaces/NexNoor/PoultryShieldAI/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/NexNoor/PoultryShieldAI/resolve/main/utils.py
4.4 kB
| import gradio as gr | |
| import importlib.util | |
| import sys | |
| import requests | |
| from PIL import Image | |
| from io import BytesIO | |
| import time, random, string | |
| from urllib.parse import urlparse, parse_qs | |
| import os | |
| def delete_all_files_in_folder(folder_path): | |
| try: | |
| current_dir = os.path.dirname(os.path.abspath(__file__)) | |
| # Resolve the path to the parent directory's 'uploads' folder | |
| upload_dir = os.path.join(current_dir, 'uploads') | |
| # Check if the folder exists | |
| if not os.path.exists(upload_dir): | |
| raise FileNotFoundError(f"The folder '{upload_dir}' does not exist.") | |
| # List all files in the folder | |
| for filename in os.listdir(upload_dir): | |
| file_path = os.path.join(upload_dir, filename) | |
| # Check if it's a file (not a directory) | |
| if os.path.isfile(file_path): | |
| os.remove(file_path) | |
| print(f"Deleted file: {file_path}") | |
| print("All files have been deleted.") | |
| except Exception as e: | |
| print(f"Error: {str(e)}") | |
| def saveImg(path_name, image_url): | |
| delete_all_files_in_folder(path_name) | |
| os.makedirs(path_name, exist_ok=True) | |
| # Parse the URL to get the actual filename without query parameters | |
| parsed_url = urlparse(image_url) | |
| filename = os.path.basename(parsed_url.path) | |
| # Ensure we have a valid file extension | |
| if not filename.endswith(('.jpg', '.jpeg', '.png', '.gif')): | |
| raise ValueError("Invalid image format. Only .jpg, .jpeg, .png, .gif are supported.") | |
| # Generate a unique filename | |
| unique_filename = generate_unique_filename(filename) | |
| file_path = os.path.join(path_name, unique_filename) | |
| # Download the image from the URL | |
| response = requests.get(image_url) | |
| if response.status_code != 200: | |
| raise Exception(f"Failed to download image. Status code: {response.status_code}") | |
| # Open the image using PIL | |
| img = Image.open(BytesIO(response.content)) | |
| # Save the image to the specified directory with the unique filename | |
| img.save(file_path) | |
| # Log all files in the uploads directory | |
| files_in_uploads = os.listdir(path_name) | |
| log_message = f"Files in uploads directory after saving:\n{', '.join(files_in_uploads)}" | |
| print(log_message) # Print to console | |
| print(f"Hello! The image has been saved to {file_path}.\n\n{log_message}", Image.open(file_path)) | |
| def generate_unique_filename(original_filename): | |
| # Get the file extension | |
| _, extension = os.path.splitext(original_filename) | |
| # Generate a timestamp | |
| timestamp = time.strftime("%Y%m%d-%H%M%S") | |
| # Generate a random string | |
| random_string = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6)) | |
| # Combine all parts to create a unique filename | |
| unique_filename = f"{timestamp}-{random_string}{extension}" | |
| return unique_filename | |
| def get_adapter(file_path): | |
| try: | |
| # Ensure the file path exists | |
| if not os.path.isfile(file_path): | |
| raise FileNotFoundError(f"File '{file_path}' not found.") | |
| # Extract the module name from the file path | |
| module_name = os.path.basename(file_path).split('.')[0] | |
| # Create the spec | |
| spec = importlib.util.spec_from_file_location(module_name, file_path) | |
| # Handle case where spec is None | |
| if spec is None: | |
| raise ImportError(f"Could not create a spec for module '{module_name}' from '{file_path}'") | |
| # Create the module | |
| module = importlib.util.module_from_spec(spec) | |
| # Add the module to sys.modules | |
| sys.modules[module_name] = module | |
| # Execute the module | |
| spec.loader.exec_module(module) | |
| return module | |
| except Exception as e: | |
| raise ValueError(f"Failed to import module from '{file_path}': {str(e)}") | |
| # Directory where files will be saved | |
| def switch_case_dict(argument): | |
| switcher = { | |
| "sequential": "./sequential-algo/predict.py", | |
| "efficient_net": "./efficientNet-algo/predict.py", | |
| } | |
| return switcher.get(argument, "Invalid month") | |
| def get_pwd(): | |
| # Define the path relative to the script's directory | |
| return os.path.dirname(os.path.abspath(__file__)) | |
| def get_path(relative_path='../uploads'): | |
| upload_dir = os.path.join(get_pwd(),relative_path) | |
| # Get the absolute path to the uploads directory | |
| return os.path.abspath(upload_dir) |