Skip to content

Commit b0f792c

Browse files
committed
first releas
1 parent e3014b3 commit b0f792c

File tree

10 files changed

+274
-1
lines changed

10 files changed

+274
-1
lines changed

PyTextBin.egg-info/PKG-INFO

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
Metadata-Version: 2.1
2+
Name: PyTextBin
3+
Version: 0.0.2
4+
Summary: PyTextBin is a versatile Python library facilitating seamless conversion between text, binary, JSON, base64, xml and CSV formats with ease.
5+
Author: Collins O. Odhiambo
6+
Author-email: <[email protected]>
7+
Keywords: python,csv,xmml,base64,text,json,binary
8+
Classifier: Development Status :: 1 - Planning
9+
Classifier: Intended Audience :: Developers
10+
Classifier: Programming Language :: Python :: 3
11+
Classifier: Operating System :: Unix
12+
Classifier: Operating System :: MacOS :: MacOS X
13+
Classifier: Operating System :: Microsoft :: Windows
14+
License-File: LICENSE
15+
Requires-Dist: opencv-python
16+
Requires-Dist: pyautogui
17+
Requires-Dist: pyaudio

PyTextBin.egg-info/SOURCES.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
LICENSE
2+
README.md
3+
setup.py
4+
PyTextBin.egg-info/PKG-INFO
5+
PyTextBin.egg-info/SOURCES.txt
6+
PyTextBin.egg-info/dependency_links.txt
7+
PyTextBin.egg-info/requires.txt
8+
PyTextBin.egg-info/top_level.txt
9+
pytextbin/__init__.py
10+
pytextbin/pytextbin.py
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

PyTextBin.egg-info/requires.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
opencv-python
2+
pyautogui
3+
pyaudio

PyTextBin.egg-info/top_level.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pytextbin

build/lib/pytextbin/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__all__ = ["pytextbin"]

build/lib/pytextbin/pytextbin.py

Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
import json
2+
import base64
3+
from typing import Union
4+
import csv
5+
import xml.etree.ElementTree as ET
6+
7+
class Textbin:
8+
"""
9+
A class for converting between various text formats.
10+
11+
Methods:
12+
- to_binary: Converts text to binary representation.
13+
- to_text: Converts binary representation to text.
14+
- json_to_base64: Converts a JSON object to a base64-encoded string.
15+
- base64_to_json: Converts a base64-encoded string to a JSON object.
16+
- xml_to_json: Converts an XML string to a JSON object.
17+
- json_to_xml: Converts a JSON object to an XML string.
18+
- xml_to_csv: Converts an XML string to a CSV file.
19+
"""
20+
def __init__(self):
21+
pass
22+
23+
def to_binary(self, text: str) -> str:
24+
"""Convert text to binary representation."""
25+
binary = " ".join(format(ord(i), "b") for i in str(text))
26+
return binary
27+
28+
def to_text(self, binary: str) -> str:
29+
"""Convert binary representation to text."""
30+
text = "".join(chr(int(i, 2)) for i in binary.split())
31+
return text
32+
33+
def json_to_base64(self, json_data: Union[dict, list]) -> str:
34+
"""Convert a JSON object to base64-encoded string."""
35+
try:
36+
data = json.dumps(json_data)
37+
base64_encoded = base64.b64encode(data.encode()).decode()
38+
return base64_encoded
39+
except json.JSONDecodeError as e:
40+
raise ValueError(f"Invalid JSON data: {e}")
41+
except Exception as e:
42+
raise ValueError(f"Error encoding to base64: {e}")
43+
44+
def base64_to_json(self, base64_string: str) -> Union[dict, list]:
45+
"""Convert a base64-encoded string to a JSON object."""
46+
try:
47+
base64_decode = base64.b64decode(base64_string).decode()
48+
json_data = json.loads(base64_decode)
49+
return json_data
50+
except base64.binascii.Error as e:
51+
raise ValueError(f"Invalid base64 data: {e}")
52+
except json.JSONDecodeError as e:
53+
raise ValueError(f"Invalid JSON data: {e}")
54+
except Exception as e:
55+
raise ValueError(f"Error decoding from base64: {e}")
56+
57+
def csv_to_json(self, csv_string: str) -> Union[dict, list]:
58+
"""Convert a CSV string to a JSON object."""
59+
try:
60+
csv_data = csv.reader(csv_string.splitlines())
61+
headers = next(csv_data)
62+
json_data = []
63+
for row in csv_data:
64+
row_dict = {}
65+
for i, value in enumerate(row):
66+
row_dict[headers[i]] = value
67+
json_data.append(row_dict)
68+
return json_data
69+
except csv.Error as e:
70+
raise ValueError(f"Invalid CSV data: {e}")
71+
except Exception as e:
72+
raise ValueError(f"Error converting CSV to JSON: {e}")
73+
74+
def json_to_csv(self, json_data: Union[dict, list]) -> str:
75+
"""Convert a JSON object to a CSV string."""
76+
try:
77+
if isinstance(json_data, list) and len(json_data) > 0:
78+
headers = list(json_data[0].keys())
79+
csv_string = ",".join(headers) + "\n"
80+
for item in json_data:
81+
csv_string += ",".join(str(item.get(header, "")) for header in headers) + "\n"
82+
return csv_string
83+
else:
84+
raise ValueError("JSON data must be a non-empty list of dictionaries")
85+
except Exception as e:
86+
raise ValueError(f"Error converting JSON to CSV: {e}")
87+
88+
def csv_to_text(self, csv_string: str) -> str:
89+
"""Convert a CSV string to plain text."""
90+
try:
91+
return csv_string
92+
except Exception as e:
93+
raise ValueError(f"Error converting CSV to text: {e}")
94+
95+
def text_to_csv(self, text: str) -> str:
96+
"""Convert plain text to a CSV string."""
97+
try:
98+
return text
99+
except Exception as e:
100+
raise ValueError(f"Error converting text to CSV: {e}")
101+
102+
def csv_to_bin(self, csv_string: str) -> str:
103+
"""Convert a CSV string to binary representation."""
104+
try:
105+
binary = self.to_binary(csv_string)
106+
return binary
107+
except Exception as e:
108+
raise ValueError(f"Error converting CSV to binary: {e}")
109+
110+
def bin_to_csv(self, binary: str) -> str:
111+
"""Convert binary representation to a CSV string."""
112+
try:
113+
csv_string = self.to_text(binary)
114+
return csv_string
115+
except Exception as e:
116+
raise ValueError(f"Error converting binary to CSV: {e}")
117+
118+
def json_to_bin(self, json_data: Union[dict, list]) -> str:
119+
"""Convert a JSON object to binary representation."""
120+
try:
121+
json_string = json.dumps(json_data)
122+
binary = self.to_binary(json_string)
123+
return binary
124+
except json.JSONDecodeError as e:
125+
raise ValueError(f"Invalid JSON data: {e}")
126+
except Exception as e:
127+
raise ValueError(f"Error converting JSON to binary: {e}")
128+
129+
def bin_to_json(self, binary: str) -> Union[dict, list]:
130+
"""Convert binary representation to a JSON object."""
131+
try:
132+
json_string = self.to_text(binary)
133+
json_data = json.loads(json_string)
134+
return json_data
135+
except json.JSONDecodeError as e:
136+
raise ValueError(f"Invalid JSON data: {e}")
137+
except Exception as e:
138+
raise ValueError(f"Error converting binary to JSON: {e}")
139+
140+
141+
def xml_to_json(self, xml_string: str) -> Union[dict, list]:
142+
"""Convert an XML string to a JSON object."""
143+
try:
144+
root = ET.fromstring(xml_string)
145+
json_data = self._element_to_dict(root)
146+
return json_data
147+
except ET.ParseError as e:
148+
raise ValueError(f"Invalid XML data: {e}")
149+
except Exception as e:
150+
raise ValueError(f"Error converting from XML to JSON: {e}")
151+
152+
def json_to_xml(self, json_data: Union[dict, list]) -> str:
153+
"""Convert a JSON object to an XML string."""
154+
try:
155+
root = self._dict_to_element(json_data)
156+
xml_string = ET.tostring(root, encoding="unicode")
157+
return xml_string
158+
except Exception as e:
159+
raise ValueError(f"Error converting from JSON to XML: {e}")
160+
161+
def xml_to_csv(self, xml_string: str, csv_file: str) -> None:
162+
"""Convert an XML string to a CSV file."""
163+
try:
164+
root = ET.fromstring(xml_string)
165+
with open(csv_file, "w", newline="", encoding="utf-8") as f:
166+
writer = csv.writer(f)
167+
header = []
168+
for child in root:
169+
row = []
170+
for key, value in child.attrib.items():
171+
if key not in header:
172+
header.append(key)
173+
row.append(value)
174+
writer.writerow(row)
175+
writer.writerow(header)
176+
except ET.ParseError as e:
177+
raise ValueError(f"Invalid XML data: {e}") from e
178+
except Exception as e:
179+
raise ValueError(f"Error converting from XML to CSV: {e}") from e
180+
181+
182+
def _element_to_dict(self, element: ET.Element) -> Union[dict, list]:
183+
"""Convert an ElementTree element to a dictionary."""
184+
if element:
185+
if element.attrib:
186+
return {element.tag: element.attrib}
187+
children = element.getchildren()
188+
if children:
189+
out = {}
190+
for child in children:
191+
result = self._element_to_dict(child)
192+
if child.tag in out:
193+
if isinstance(out[child.tag], list):
194+
out[child.tag].append(result)
195+
else:
196+
out[child.tag] = [out[child.tag], result]
197+
else:
198+
out[child.tag] = result
199+
return {element.tag: out}
200+
return {element.tag: element.text}
201+
return None
202+
203+
def _dict_to_element(self, data: Union[dict, list]) -> ET.Element:
204+
"""Convert a dictionary to an ElementTree element."""
205+
if isinstance(data, dict):
206+
items = data.items()
207+
elif isinstance(data, list):
208+
items = enumerate(data)
209+
else:
210+
raise ValueError(f"Invalid data type: {type(data)}")
211+
elem = ET.Element("item")
212+
for key, value in items:
213+
if isinstance(value, dict):
214+
child = self._dict_to_element(value)
215+
child.tag = key
216+
elem.append(child)
217+
elif isinstance(value, list):
218+
for item in value:
219+
child = self._dict_to_element(item)
220+
child.tag = key
221+
elem.append(child)
222+
else:
223+
child = ET.Element(key)
224+
child.text = str(value)
225+
elem.append(child)
226+
return elem
227+
228+
if __name__ == "__main__":
229+
textbin = Textbin()
230+
word = {"foo": "bar"}
231+
232+
try:
233+
converted_word = textbin.json_to_base64(word)
234+
print(converted_word) # Output: eyJmb28iOiAiYmFyIn0=
235+
BASE64_STRING = "eyJmb28iOiAiYmFyIn0="
236+
converted_binary = textbin.base64_to_json(BASE64_STRING)
237+
print(converted_binary) # Output: {'foo': 'bar'}
238+
239+
except ValueError as e:
240+
print(f"Error: {e}")
4.31 KB
Binary file not shown.

dist/PyTextBin-0.0.2.tar.gz

4.75 KB
Binary file not shown.

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
here = os.path.abspath(os.path.dirname(__file__))
66

77
with codecs.open(os.path.join(here, "README.md"), encoding="utf-8") as fh:
8-
long_description = "\n" + fh.read()
8+
DESCRIPTION = "\n" + fh.read()
99

1010
VERSION = '0.0.2'
1111
DESCRIPTION = 'PyTextBin is a versatile Python library facilitating seamless conversion between text, binary, JSON, base64, xml and CSV formats with ease.'

0 commit comments

Comments
 (0)