buttercutter commited on
Commit
8c19222
·
verified ·
1 Parent(s): e7ed69a

Upload postprocess_jsonl_latest.py

Browse files
Files changed (1) hide show
  1. postprocess_jsonl_latest.py +29 -126
postprocess_jsonl_latest.py CHANGED
@@ -26,144 +26,47 @@ from sentence_transformers import SentenceTransformer
26
  import torch
27
 
28
  # --- IPFS CID Generation Code (from provided ipfs_multiformats.py) ---
 
29
  import hashlib
30
  from multiformats import CID, multihash
31
  import tempfile
 
32
  import sys
33
-
34
  class ipfs_multiformats_py:
35
- def __init__(self, resources=None, metadata=None):
36
  self.multihash = multihash
37
- # Added error handling for multihash version/import
38
- if not hasattr(self.multihash, 'wrap') or not hasattr(self.multihash, 'decode'):
39
- logging.warning("Multihash library structure might have changed. CID generation may fail.")
40
  return None
41
 
 
42
  def get_file_sha256(self, file_path):
43
  hasher = hashlib.sha256()
44
- try:
45
- with open(file_path, 'rb') as f:
46
- while chunk := f.read(8192):
47
- hasher.update(chunk)
48
- return hasher.digest()
49
- except Exception as e:
50
- logging.error(f"Error hashing file {file_path}: {e}")
51
- return None
52
-
53
- # Takes bytes input directly
54
- def get_bytes_sha256(self, data_bytes: bytes):
55
- hasher = hashlib.sha256()
56
- hasher.update(data_bytes)
57
  return hasher.digest()
58
 
59
- def get_multihash_sha256(self, content_hash):
60
- if content_hash is None:
61
- return None
62
- try:
63
- # Try using multihash.digest instead of wrap
64
- mh = self.multihash.digest(content_hash, 'sha2-256')
65
- return mh
66
- except Exception as e:
67
- logging.error(f"Error creating multihash: {e}")
68
- return None
69
-
70
- def get_multihash_sha256_old(self, content_hash):
71
- if content_hash is None:
72
- return None
73
- try:
74
- # Use 'sha2-256' which corresponds to code 0x12
75
- #mh = self.multihash.wrap(code='sha2-256', digest=content_hash)
76
- mh = self.multihash.wrap('sha2-256', content_hash)
77
- return mh
78
- except Exception as e:
79
- logging.error(f"Error wrapping hash in multihash: {e}")
80
- return None
81
-
82
- def get_cid_old(self, data):
83
- """Generates CID v1 base32 for bytes data or file path."""
84
- mh = None
85
- try:
86
- if isinstance(data, (str, Path)) and os.path.isfile(data):
87
- # logging.debug(f"Calculating CID for file: {data}")
88
- file_content_hash = self.get_file_sha256(data)
89
  mh = self.get_multihash_sha256(file_content_hash)
90
- elif isinstance(data, bytes):
91
- # logging.debug(f"Calculating CID for bytes (length: {len(data)})")
92
- bytes_hash = self.get_bytes_sha256(data)
93
- mh = self.get_multihash_sha256(bytes_hash)
94
- elif isinstance(data, str):
95
- # logging.debug(f"Calculating CID for string (length: {len(data)})")
96
- # Treat string as UTF-8 bytes
97
- bytes_hash = self.get_bytes_sha256(data.encode('utf-8'))
98
- mh = self.get_multihash_sha256(bytes_hash)
99
- else:
100
- logging.warning(f"Unsupported data type for CID generation: {type(data)}. Skipping CID.")
101
- return None
102
-
103
- if mh:
104
- # CIDv1, base32, raw codec (0x55)
105
- cid = CID(base='base32', version=1, codec='raw', multihash=mh)
106
- return str(cid)
107
- else:
108
- return None
109
- except Exception as e:
110
- logging.error(f"Error generating CID: {e}", exc_info=False)
111
- return None
112
-
113
- def get_cid(self, data):
114
- """Generates CID v1 base32 for bytes data or file path."""
115
- try:
116
- # Get the hash first
117
- content_hash = None
118
- if isinstance(data, (str, Path)) and os.path.isfile(data):
119
- content_hash = self.get_file_sha256(data)
120
- elif isinstance(data, bytes):
121
- content_hash = self.get_bytes_sha256(data)
122
- elif isinstance(data, str):
123
- content_hash = self.get_bytes_sha256(data.encode('utf-8'))
124
- else:
125
- logging.warning(f"Unsupported data type for CID generation: {type(data)}. Skipping CID.")
126
- return None
127
-
128
- if not content_hash:
129
- return None
130
-
131
- # Try the new CID API format
132
- try:
133
- # Version 1 of multiformats may use from_digest or other method instead of passing multihash directly
134
- from multiformats import multihash
135
- digest = multihash.digest(content_hash, 'sha2-256')
136
- cid = CID.from_digest(digest, 'raw') # Try this format first
137
- return str(cid)
138
- except (AttributeError, TypeError):
139
- try:
140
- # Try alternate creation method
141
- mh = self.get_multihash_sha256(content_hash)
142
- cid = CID(version=1, codec='raw', hash=mh) # Try with hash parameter
143
- return str(cid)
144
- except:
145
- # Fallback to simple base64 encoding if CID creation fails
146
- import base64
147
- b64_hash = base64.b64encode(content_hash).decode('ascii')
148
- return f"sha256:{b64_hash}"
149
-
150
- except Exception as e:
151
- logging.error(f"Error generating CID: {e}", exc_info=False)
152
- # Fallback to a simple hash representation
153
- try:
154
- if isinstance(data, (str, Path)) and os.path.isfile(data):
155
- content_hash = self.get_file_sha256(data)
156
- elif isinstance(data, bytes):
157
- content_hash = self.get_bytes_sha256(data)
158
- elif isinstance(data, str):
159
- content_hash = self.get_bytes_sha256(data.encode('utf-8'))
160
- else:
161
- return None
162
-
163
- import base64
164
- return f"sha256:{base64.b64encode(content_hash).decode('ascii')}"
165
- except:
166
- return None
167
  # --- End IPFS CID Code ---
168
 
169
 
@@ -1049,7 +952,7 @@ def create_embedding_dataset(
1049
  logging.info(f"Using CPU (no GPU acceleration available)")
1050
 
1051
  model = SentenceTransformer(embedding_model_name, device=device)
1052
- cid_generator = ipfs_multiformats_py() # Initialize CID generator
1053
  logging.info("Embedding model & CID generator loaded.")
1054
  except Exception as e:
1055
  logging.error(f"Failed to load embedding model or init CID generator: {e}", exc_info=True)
 
26
  import torch
27
 
28
  # --- IPFS CID Generation Code (from provided ipfs_multiformats.py) ---
29
+ # https://github.com/endomorphosis/ipfs_accelerate_py/blob/5f88e36551b626e99b05bd4bd8a3e043c5c0e8c9/ipfs_accelerate_py/ipfs_multiformats.py#L25
30
  import hashlib
31
  from multiformats import CID, multihash
32
  import tempfile
33
+ import os
34
  import sys
 
35
  class ipfs_multiformats_py:
36
+ def __init__(self, resources, metadata):
37
  self.multihash = multihash
 
 
 
38
  return None
39
 
40
+ # Step 1: Hash the file content with SHA-256
41
  def get_file_sha256(self, file_path):
42
  hasher = hashlib.sha256()
43
+ with open(file_path, 'rb') as f:
44
+ while chunk := f.read(8192):
45
+ hasher.update(chunk)
 
 
 
 
 
 
 
 
 
 
46
  return hasher.digest()
47
 
48
+ # Step 2: Wrap the hash in Multihash format
49
+ def get_multihash_sha256(self, file_content_hash):
50
+ mh = self.multihash.wrap(file_content_hash, 'sha2-256')
51
+ return mh
52
+
53
+ # Step 3: Generate CID from Multihash (CIDv1)
54
+ def get_cid(self, file_data):
55
+ if os.path.isfile(file_data) == True:
56
+ absolute_path = os.path.abspath(file_data)
57
+ file_content_hash = self.get_file_sha256(file_data)
58
+ mh = self.get_multihash_sha256(file_content_hash)
59
+ cid = CID('base32', 'raw', mh)
60
+ else:
61
+ with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
62
+ filename = f.name
63
+ with open(filename, 'w') as f_new:
64
+ f_new.write(file_data)
65
+ file_content_hash = self.get_file_sha256(filename)
 
 
 
 
 
 
 
 
 
 
 
 
66
  mh = self.get_multihash_sha256(file_content_hash)
67
+ cid = CID('base32', 1, 'raw', mh)
68
+ os.remove(filename)
69
+ return str(cid)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  # --- End IPFS CID Code ---
71
 
72
 
 
952
  logging.info(f"Using CPU (no GPU acceleration available)")
953
 
954
  model = SentenceTransformer(embedding_model_name, device=device)
955
+ cid_generator = ipfs_multiformats_py(resources=None, metadata=None) # Initialize CID generator
956
  logging.info("Embedding model & CID generator loaded.")
957
  except Exception as e:
958
  logging.error(f"Failed to load embedding model or init CID generator: {e}", exc_info=True)