MCPcopy Create free account
hub / github.com/modelscope/ms-agent / text_hash

Function text_hash

ms_agent/utils/utils.py:261–288  ·  view source on GitHub ↗

Encodes a given text using SHA256 and returns the last 8 characters of the hexadecimal representation. Args: text (str): The input string to be encoded. keep_n_chars (int): The number of characters to keep from the end of the hash. Returns: str: The last 8

(text: str, keep_n_chars: int = 8)

Source from the content-addressed store, hash-verified

259
260
261def text_hash(text: str, keep_n_chars: int = 8) -> str:
262 """
263 Encodes a given text using SHA256 and returns the last 8 characters
264 of the hexadecimal representation.
265
266 Args:
267 text (str): The input string to be encoded.
268 keep_n_chars (int): The number of characters to keep from the end of the hash.
269
270 Returns:
271 str: The last 8 characters of the SHA256 hash in hexadecimal,
272 or an empty string if the input is invalid.
273 """
274 try:
275 # Encode the text to bytes (UTF-8 is a common choice)
276 text_bytes = text.encode('utf-8')
277
278 # Calculate the SHA256 hash
279 sha256_hash = hashlib.sha256(text_bytes)
280
281 # Get the hexadecimal representation of the hash
282 hex_digest = sha256_hash.hexdigest()
283
284 # Return the last 8 characters
285 return hex_digest[-keep_n_chars:]
286 except Exception as e:
287 logger.error(f'Error generating hash for text: {text}. Error: {e}')
288 return ''
289
290
291def json_loads(text: str) -> dict:

Callers 3

_preprocessMethod · 0.90
runMethod · 0.90

Calls 1

encodeMethod · 0.80

Tested by

no test coverage detected