Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pip install backgroundremover error #103

Open
dcnc336 opened this issue Oct 20, 2023 · 9 comments
Open

pip install backgroundremover error #103

dcnc336 opened this issue Oct 20, 2023 · 9 comments

Comments

@dcnc336
Copy link

dcnc336 commented Oct 20, 2023

When I run command pip install backgroundremover, I keep getting this error

ERROR: Exception:
Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/urllib3/response.py", line 438, in _error_catcher
    yield
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/urllib3/response.py", line 561, in read
    data = self._fp_read(amt) if not fp_closed else b""
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/urllib3/response.py", line 527, in _fp_read
    return self._fp.read(amt) if amt is not None else self._fp.read()
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 102, in read
    self.__buf.write(data)
  File "/usr/lib/python3.10/tempfile.py", line 622, in func_wrapper
    return func(*args, **kwargs)
OSError: [Errno 28] No space left on device

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/cli/base_command.py", line 180, in exc_logging_wrapper
    status = run_func(*args)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/cli/req_command.py", line 245, in wrapper
    return func(self, options, args)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/commands/install.py", line 377, in run
    requirement_set = resolver.resolve(
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 95, in resolve
    result = self._result = resolver.resolve(
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/resolvelib/resolvers.py", line 546, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/resolvelib/resolvers.py", line 427, in resolve
    failure_causes = self._attempt_to_pin_criterion(name)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/resolvelib/resolvers.py", line 239, in _attempt_to_pin_criterion
    criteria = self._get_updated_criteria(candidate)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/resolvelib/resolvers.py", line 230, in _get_updated_criteria
    self._add_to_criteria(criteria, requirement, parent=candidate)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/resolvelib/resolvers.py", line 173, in _add_to_criteria
    if not criterion.candidates:
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/resolvelib/structs.py", line 156, in __bool__
    return bool(self._sequence)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 155, in __bool__
    return any(self)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 143, in <genexpr>
    return (c for c in iterator if id(c) not in self._incompatible_ids)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 47, in _iter_built
    candidate = func()
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/resolution/resolvelib/factory.py", line 211, in _make_candidate_from_link
    self._link_candidate_cache[link] = LinkCandidate(
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 293, in __init__
    super().__init__(
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 156, in __init__
    self.dist = self._prepare()
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 225, in _prepare
    dist = self._prepare_distribution()
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 304, in _prepare_distribution
    return preparer.prepare_linked_requirement(self._ireq, parallel_builds=True)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/operations/prepare.py", line 525, in prepare_linked_requirement
    return self._prepare_linked_requirement(req, parallel_builds)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/operations/prepare.py", line 596, in _prepare_linked_requirement
    local_file = unpack_url(
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/operations/prepare.py", line 168, in unpack_url
    file = get_http_url(
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/operations/prepare.py", line 109, in get_http_url
    from_path, content_type = download(link, temp_dir.path)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/network/download.py", line 147, in __call__
    for chunk in chunks:
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/cli/progress_bars.py", line 53, in _rich_progress_bar
    for chunk in iterable:
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_internal/network/utils.py", line 63, in response_chunks
    for chunk in response.raw.stream(
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/urllib3/response.py", line 622, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/urllib3/response.py", line 560, in read
    with self._error_catcher():
  File "/usr/lib/python3.10/contextlib.py", line 153, in __exit__
    self.gen.throw(typ, value, traceback)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/urllib3/response.py", line 455, in _error_catcher
    raise ProtocolError("Connection broken: %r" % e, e)
pip._vendor.urllib3.exceptions.ProtocolError: ("Connection broken: OSError(28, 'No space left on device')", OSError(28, 'No space left on device'))
@nadermx
Copy link
Owner

nadermx commented Oct 20, 2023 via email

@dcnc336
Copy link
Author

dcnc336 commented Oct 20, 2023

Thank you for quick answer @nadermx !
I am running python server on AWS now, how much space is it needed approximately? 30G is enough?

@nadermx
Copy link
Owner

nadermx commented Oct 20, 2023 via email

@dcnc336
Copy link
Author

dcnc336 commented Oct 20, 2023

import os
from flask import Flask, request, jsonify, send_file ,make_response,render_template
from flask_cors import CORS
from time import perf_counter
from backgroundremover import utilities
from backgroundremover.bg import remove

def remove_image_background(input_path, output_path, debugger=False):
    ''' NOTE: Models and modules will take some extra time to load during your first execution.\n
        NOTE: If you want to play around with the default parameters, check https://github.com/nadermx/backgroundremover see what they mean.\n
        Set 'debugger=True' to see execution debugs.\n
    '''

    # Set default parameters for background remover function.
    default_parameters = {
    'model': 'u2net',
    'alpha_matting': False,
    'alpha_matting_foreground_threshold': 240,
    'alpha_matting_background_threshold': 10,
    'alpha_matting_erode_size': 10,
    'alpha_matting_base_size': 1000,
    }

    # Convert paths to absolute paths.
    input_path, output_path = os.path.abspath(input_path), os.path.abspath(output_path)

    # Check if paths exist.
    if not os.path.exists(input_path):
        raise OSError(f'Path {input_path} does not exist.')
    if not os.path.exists(os.path.dirname(output_path)):
        raise OSError(f'Path {output_path} does not exist.')
    
    # Load modules if running for the first time.
    if 'modules_imported' not in globals():
        global modules_imported, remove, utilities
        if debugger: print("Running app for the first time, importing modules.")
        
        modules_imported = ''

    # Open input image.
    with open(input_path, 'rb') as file:
        image = file.read()

    # Load model for the first time.
    if 'model_loaded' not in globals():
        global model_loaded
        if debugger: print('Loading model...')
        model_loaded = ''
    
    # Remove background from the image and return it as a bytes object.
    t1 = perf_counter()
    img_removed_bg_bytes = remove(image, model_name=default_parameters['model'],alpha_matting=default_parameters['alpha_matting'], alpha_matting_foreground_threshold=default_parameters['alpha_matting_foreground_threshold'],alpha_matting_background_threshold=default_parameters['alpha_matting_background_threshold'],alpha_matting_erode_structure_size=default_parameters['alpha_matting_erode_size'],alpha_matting_base_size=default_parameters['alpha_matting_base_size'])
    if debugger: print(f"{output_path} done. Took {(perf_counter()-t1):003} seconds.")

    # Write bytes object to your output path.
    with open(output_path, 'wb') as file:
        file.write(img_removed_bg_bytes)

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'

CORS(app)

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    if file:
        print(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
        remove_image_background(f"uploads/{file.filename}", f"outputs/{file.filename}")
        return make_response(send_file(f"outputs/{file.filename}",download_name=file.filename,as_attachment=True))

if __name__ == '__main__':
    app.run(host='0.0.0.0',port='8000', debug=True)

I am using Flask python server now, and the backgroundremover library was not installed by above issues, Could you please explain what you mean file?

@nadermx
Copy link
Owner

nadermx commented Oct 20, 2023 via email

@dcnc336
Copy link
Author

dcnc336 commented Oct 20, 2023

Hi @nadermx , quick question for me, I am going to increase volume with 15G, do you think Is this enough to install this library?

@nadermx
Copy link
Owner

nadermx commented Oct 20, 2023 via email

@dcnc336
Copy link
Author

dcnc336 commented Oct 20, 2023

Ok, Ill try with that, Thank you for your quick answer!

@dcnc336
Copy link
Author

dcnc336 commented Oct 20, 2023

Hi @nadermx, I increased the storage size with 15G, and backgroundremover library installed successfully, but when run my above code, I am getting error, Could you please check this error out?

[20/Oct/2023 12:35:35] "POST /upload HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.10/site-packages/flask/app.py", line 1478, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/flask/app.py", line 1458, in wsgi_app
    response = self.handle_exception(e)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/flask_cors/extension.py", line 176, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/home/ubuntu/.local/lib/python3.10/site-packages/flask/app.py", line 1455, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/ubuntu/.local/lib/python3.10/site-packages/flask/app.py", line 869, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/flask_cors/extension.py", line 176, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/home/ubuntu/.local/lib/python3.10/site-packages/flask/app.py", line 867, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/ubuntu/.local/lib/python3.10/site-packages/flask/app.py", line 852, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/var/www/remove-bg-app/_server/app.py", line 75, in upload_file
    remove_image_background(f"uploads/{file.filename}", f"outputs/{file.filename}")
  File "/var/www/remove-bg-app/_server/app.py", line 51, in remove_image_background
    img_removed_bg_bytes = remove(image, model_name=default_parameters['model'],alpha_matting=default_parameters['alpha_matting'], alpha_matting_foreground_threshold=default_parameters['alpha_matting_foreground_threshold'],alpha_matting_background_threshold=default_parameters['alpha_matting_background_threshold'],alpha_matting_erode_structure_size=default_parameters['alpha_matting_erode_size'],alpha_matting_base_size=default_parameters['alpha_matting_base_size'])
  File "/home/ubuntu/.local/lib/python3.10/site-packages/backgroundremover/bg.py", line 184, in remove
    img = Image.open(io.BytesIO(data)).convert("RGB")
  File "/home/ubuntu/.local/lib/python3.10/site-packages/PIL/Image.py", line 3305, in open
    raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f2c7e08d990>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants