File size: 4,397 Bytes
9639b82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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)