-
Notifications
You must be signed in to change notification settings - Fork 5
/
removebg.py
138 lines (118 loc) · 4.6 KB
/
removebg.py
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
135
136
137
138
import json
import requests
from rich.console import Console
from cmds import parsecmds
console = Console()
# pasring commands
arguments = parsecmds()
class Api_stuff:
"""
Class with methods to save api key and Read stored key
"""
@staticmethod
def save_api_key() -> None:
"""
Saves api key to file
"""
with open(".apikey.txt", "w") as f:
f.write(input("🤦No api key saved found, Input Key: ").strip())
console.print(
"Api key saved successfully:White_Heavy_Check_Mark: Restart the Program :glowing_star: "
)
exit()
@staticmethod
def read_stored_Api():
"""
Reads api key from file
"""
try:
with open(".apikey.txt", "r") as f:
key = f.read()
return key
except FileNotFoundError:
# console.print_exception(show_locals=True)
Api_stuff.save_api_key()
class Other_stuff:
"""
Class with methods to save Bg Removed images and print formatted errors
"""
@staticmethod
def save_image(filename, image) -> None:
"""
Saves image to file
"""
with open(filename, "wb") as out:
out.write(image)
console.print(
f":White_Heavy_Check_Mark: [bold green]Background Removed and Saved Image successfully with name {filename} :winking_face: [/bold green]"
)
@staticmethod
def print_error(error) -> None:
"""
Prints formatted error
"""
json_response = json.loads(error)
error_detail_dict = json_response["errors"][0]
got_an_error = f"""
:sob: [bold yellow] Error [/bold yellow]: [red] {error_detail_dict.get('title')} [/red]
:thinking_face: [bold yellow] Reason [/bold yellow]: [red] {error_detail_dict.get('code')} [/red]
:page_with_curl: [bold yellow] Detail [/bold yellow]: [red] {error_detail_dict.get('detail')} [/red]
"""
console.print(got_an_error)
class Remove_background:
"""
Main class to remove background and that calls other classes"""
def __init__(self):
try:
self.key = Api_stuff().read_stored_Api()
except FileNotFoundError:
Api_stuff().save_api_key()
def remove(self) -> None:
"""
method to remove background
"""
with console.status("[bold green] Removing Background") as status:
if (arguments.img).startswith("http"):
console.print(" [bold yellow] Uploading Image From URL")
response = requests.post(
"https://api.remove.bg/v1.0/removebg",
data={
"image_url": arguments.img,
"size": arguments.size,
"type": arguments.type,
"format": arguments.format,
"crop": arguments.crop,
"bg_color": arguments.bgcolor,
"bg_image_url": arguments.bgimgurl,
"bg_image_file": arguments.bgimgfile,
},
headers={"X-Api-Key": self.key},
)
if response.status_code == requests.codes.ok:
console.print("[bold yellow] Downloading Image")
Other_stuff().save_image(arguments.filename, response.content)
else:
Other_stuff().print_error(response.text)
else:
console.print(" [bold yellow] uploading image from local")
response = requests.post(
"https://api.remove.bg/v1.0/removebg",
files={"image_file": open(arguments.img, "rb")},
data={
"size": arguments.size,
"type": arguments.type,
"format": arguments.format,
"crop": arguments.crop,
"bg_color": arguments.bgcolor,
"bg_image_url": arguments.bgimgurl,
"bg_image_file": arguments.bgimgfile,
},
headers={"X-Api-Key": self.key},
)
if response.status_code == requests.codes.ok:
console.print("[bold yellow] Downloading Image")
Other_stuff().save_image(arguments.filename, response.content)
else:
Other_stuff().print_error(response.text)
if __name__ == "__main__":
Remove_background().remove()