REKTY ANJANY avatar on Tensor.Art

REKTY ANJANY

877817999405385189
HUMBLE PLEASE ?
61
Followers
6
Following
67.5K
Runs
34
Downloads
5.1K
Likes
3.2K
Stars
Latest
Most Liked
What Is an API Key?

What Is an API Key?

What Is an API Key? Definition, Functions, and How It WorksFor AI users, the term API Key may already be familiar. However, for those who are new to AI services and integrations, the concept can still be confusing.This article explains what an API Key is, how it works, why it should be kept secure, and a simple example of how it can be used in an AI generator application.What Is an API Key?An API Key is a unique code or token used to identify and authorize an application when communicating with an API (Application Programming Interface).Simply put, an API Key can be thought of as a digital access key.When an application needs to use a particular service through an API, the API Key can be included as part of the authentication process so that the server can identify and verify the request.What Is an API Key Used For?Depending on the system, an API Key can have several functions.1. IdentificationAn API Key can help a service identify which application or account is making a request.2. AuthenticationAn API Key can be used as part of the process of verifying whether a request has the appropriate access.3. Access ControlA service can use API Keys to determine which features or API endpoints can be accessed.4. Usage LimitsAn API Key can be associated with usage limits, such as a specific number of requests or a certain quota.5. Usage MonitoringAPI providers can use API Keys to track and monitor API usage.Example: Using an API Key in an AI Generator ApplicationAs a simple example, I tried creating an AI generator application that includes an API configuration feature.The application supports TAMS API Key (tams.tensor.art) as an API provider.The API Key can be entered into the application's API configuration and used according to the access provided by the API service.Example application:VisualAIArtwork.pages.devThis is a simple example of how an application can communicate with an external AI service through an API.How Does an API Key Work?The basic process can be illustrated like this:Application → API Key → API → Server → ResponseThe user enters an API Key into the application's API configuration. When the application sends a request, the API Key is used according to the authentication method required by the API service.The server then verifies the request and, if it is authorized, processes it and returns a response to the application.Why Should You Keep Your API Key Private?An API Key should be treated as sensitive information.Avoid sharing your API Key in:public posts,screenshots,comments,tutorial videos,public repositories,or anywhere else where other people can see it.If someone obtains your API Key, they may potentially use it without your permission, depending on the permissions and security system associated with that key.For this reason, always be careful when storing or displaying API Keys.Tips for Keeping Your API Key Safe1. Never share your API Key publiclyTreat your API Key as private access information.2. Hide your API Key in screenshotsIf you create a tutorial or demonstration, make sure the actual key is not visible.3. Use only the permissions you needIf the API provider offers permission controls, use the minimum access required.4. Replace a leaked API KeyIf your API Key is accidentally exposed, revoke, disable, or regenerate it as soon as possible if those options are available.ConclusionAn API Key is an important part of communication between an application and an API service.It can be used to identify applications, authenticate requests, control access, and monitor API usage.A simple example is an AI generator application that supports TAMS API Key as an API provider.Understanding API Keys is a useful first step for anyone interested in AI applications, automation, and API integrations.Treat your API Key like a digital access key and never share it publicly.
2
Safetensors File Integrity Checker: Verify LoRA & Checkpoint Files with Python

Safetensors File Integrity Checker: Verify LoRA & Checkpoint Files with Python

Safetensors File Integrity Checker — Verify LoRA & Checkpoint Files Using PythonIntroductionSafetensors files are widely used in AI image generation workflows, including LoRA models and checkpoints. A damaged or incomplete file may cause loading errors or unexpected problems when using an AI model.The Safetensors File Integrity Checker is a simple Python tool designed to verify whether a Safetensors file can be read correctly and generate a SHA-256 checksum for file identification.This tool helps users inspect their model files without modifying the original data.FeaturesCheck whether a Safetensors file exists.Verify that the file can be opened and read.Read tensor names and metadata.Generate a SHA-256 checksum.Display file size and basic information.Detect common file-reading errors.Works with LoRA and checkpoint files that use the Safetensors format.RequirementsInstall Python and the Safetensors library:pip install safetensors The script also uses Python's built-in hashlib and pathlib modules.Python ScriptCopy the following code and save it as safetensors_integrity_checker.py.import hashlib from pathlib import Path from safetensors import safe_open def calculate_sha256(file_path): sha256 = hashlib.sha256() with open(file_path, "rb") as file: while chunk := file.read(1024 * 1024): sha256.update(chunk) return sha256.hexdigest() def check_safetensors(file_path): file_path = Path(file_path) print("=" * 60) print("SAFETENSORS FILE INTEGRITY CHECKER") print("=" * 60) if not file_path.exists(): print("Status: File not found.") return if not file_path.is_file(): print("Status: The selected path is not a file.") return file_size = file_path.stat().st_size file_size_mb = file_size / (1024 * 1024) print(f"File: {file_path.name}") print(f"Size: {file_size_mb:.2f} MB") print("\n[SHA-256 CHECKSUM]") try: checksum = calculate_sha256(file_path) print(checksum) except OSError as error: print(f"Unable to calculate checksum: {error}") return print("\n[SAFETENSORS VALIDATION]") try: with safe_open( str(file_path), framework="pt", device="cpu" ) as model: tensor_names = list(model.keys()) metadata = model.metadata() print("Status: File opened successfully.") print(f"Tensor count: {len(tensor_names)}") if metadata: print("Metadata: Available") else: print("Metadata: Not available") print("\n[VALIDATION RESULT]") print("The file can be opened using Safetensors.") except Exception as error: print("Status: Unable to read the Safetensors file.") print(f"Error: {error}") print("\n" + "=" * 60) print("CHECK COMPLETE") print("=" * 60) if __name__ == "__main__": file_path = input( "Enter the path to your Safetensors file: " ).strip().strip('"') check_safetensors(file_path) How to UseInstall Python on your computer.Install the Safetensors library.Save the script as safetensors_integrity_checker.py.Open a terminal in the script's directory.Run the script:python safetensors_integrity_checker.py Enter the full path to your LoRA or checkpoint file.Wait for the script to complete the validation.Review the checksum and file-reading results.Example Output============================================================ SAFETENSORS FILE INTEGRITY CHECKER ============================================================ File: example_lora.safetensors Size: 144.25 MB [SHA-256 CHECKSUM] a1b2c3d4e5f678901234567890abcdef1234567890abcdef1234567890abcdef [SAFETENSORS VALIDATION] Status: File opened successfully. Tensor count: 128 Metadata: Available [VALIDATION RESULT] The file can be opened using Safetensors. ============================================================ CHECK COMPLETE ============================================================ Note: The checksum, file size, and tensor count in this example are illustrative. Actual results depend on the selected file.Understanding the SHA-256 ChecksumA SHA-256 checksum is a unique-looking digital fingerprint calculated from the contents of a file.It can be useful for comparing two files:If two files have the same SHA-256 checksum, they have the same contents with respect to that checksum calculation.If two files have different checksums, their contents differ.A checksum alone does not prove that a file is safe or that its model weights are correct.You can use the checksum to help identify duplicate files or compare a downloaded model against a checksum provided by a trusted source.Understanding File ValidationThis tool checks whether the Safetensors library can open and read the file header, metadata, and tensor names.A successful read indicates that the file passed the operations performed by this script. It does not guarantee that the model is compatible with every AI framework or that all model weights are semantically correct.If the script reports an error, the file may be incomplete, corrupted, unsupported by the installed library, or affected by another file-related issue.Important NotesKeep a backup of your original LoRA and checkpoint files.Do not overwrite model files during the checking process.A matching checksum is useful for verifying file identity, not for proving that the model is trustworthy.Use files from reliable sources and keep your Python dependencies updated.ConclusionThe Safetensors File Integrity Checker provides a simple way to inspect model files using Python. It combines SHA-256 checksum generation with Safetensors file-reading validation to help users understand their model files and identify potential reading problems.This tool can be useful for AI image-generation workflows involving LoRA models, checkpoints, and other Safetensors-based files.
6
What's Actually Inside a .safetensors File? Dissect It With Python in 30 Lines 🕵️

What's Actually Inside a .safetensors File? Dissect It With Python in 30 Lines 🕵️

You have hundreds of LoRA and checkpoint .safetensors files sitting on disk. Here's something most people never realize: you can "open" any of them with plain Python — no PyTorch, no safetensors library, no GPU — just Python's built-in modules. In seconds you'll know the base model, the dtype, the layer count, even how it was trained — all read from just the first few KB of the file.✅ The code in this article was tested on a real LoRA (Beauty.safetensors) — the actual output is shown below.📌 Note: this is a desktop tool — it reads files on your machine via a path. That means it can't run inside TensorArt's cloud ComfyUI workflow (its sandbox gives no file-system or free-Python access), but it runs perfectly in local ComfyUI or any terminal.🧠 THE CONCEPT, IN 2 MINUTESThe .safetensors format is refreshingly simple:[ 8 bytes ] header length (little-endian unsigned 64-bit integer)[ N bytes ] header = JSON: every tensor (name, shape, dtype)[ the rest ] raw weight dataThat's it! Because the header is plain JSON, you can read it without loading any weights — even a 20 GB file only needs its first few hundred KB touched. This is exactly why safetensors became the standard: it's safe (unlike pickle, it can't execute hidden code) and fast to inspect.🐍 THE COMPLETE SCRIPT (COPY-PASTE, RUNS AS-IS)Save as check_safetensors.py:"""Dissect a .safetensors file without PyTorch — pure standard library."""import json, struct, sysdef read_header(path):with open(path, "rb") as f:n = struct.unpack("<Q", f.read(8))[0] # first 8 bytes = header lengthheader = json.loads(f.read(n).decode("utf-8")) # header = JSONmeta = header.pop("__metadata__", {}) # training metadata, separatedreturn header, metapath = sys.argv[1] if len(sys.argv) > 1 else "model.safetensors"hdr, meta = read_header(path)print("── SUMMARY ──────────────────────────────")print(f"Tensor count : {len(hdr)}")dtypes = {}for t in hdr.values():dtypes[t["dtype"]] = dtypes.get(t["dtype"], 0) + 1print(f"Dtypes : {dtypes}")base = (meta.get("ss_base_model_version")or meta.get("modelspec.architecture", "?"))print(f"Base model : {base}")if meta.get("ss_network_module"):print(f"Trainer : {meta['ss_network_module']} "f"(rank={meta.get('ss_network_dim', '?')}, "f"alpha={meta.get('ss_network_alpha', '?')})")name, info = next(iter(hdr.items()))print(f"Example tensor : {name} {info['shape']} {info['dtype']}")📝 CREATING THE FILE (BEGINNER-FRIENDLY)Never created a Python file before? Two ways — pick one:Option A — Notepad (already on Windows):1. Open Notepad (Start → type "notepad")2. Paste the script above3. File → Save As → navigate to a folder (e.g. D:\tools)4. In the save dialog:- File name: check_safetensors.py — type it WITH QUOTES ("check_safetensors.py") so Notepad doesn't append .txt- Save as type: change to All Files (*.*)- Encoding: UTF-8⚠️ The classic beginner trap: ending up with check_safetensors.py.txt. If that happens, rename the file and delete the .txt part.Option B — VS Code (nicer, free): install VS Code (code.visualstudio.com), open a folder, create a new file named check_safetensors.py, paste, Ctrl+S. Done — no quoting tricks needed.▶️ RUNNING IT VIA POWERSHELL1. Open PowerShell (Start → type "powershell" → Enter)2. First, make sure Python exists:python --versionIf you see something like Python 3.11.x you're good. If Windows opens the Microsoft Store instead, either install Python from there (one click) or grab it from python.org — and tick "Add Python to PATH" during install.3. Go to the folder where you saved the script, then run it with the path to any .safetensors file:cd "D:\tools"python check_safetensors.py "D:\ComfyUI\models\loras\Beauty.safetensors"Two small rules:- Always quote paths that contain spaces (most model folders do)- Drag-and-drop trick: type "python check_safetensors.py " then DRAG the model file from Explorer into the PowerShell window — its full path gets pasted for you, quotes included 💡REAL OUTPUT FROM MY OWN FILE── SUMMARY ──────────────────────────────Tensor count : 792Dtypes : {'F16': 792}Base model : krea2Trainer : networks.lora_krea2 (rank=64, alpha=32.0)Example tensor : lora_unet_blocks_0_attn_gate.alpha [] F16Done in a fraction of a second — without loading a single weight.🔍 WHY IS THIS ACTUALLY USEFUL?1. Check a LoRA's base model before you use it. The ss_base_model_version metadata tells you whether the LoRA targets SDXL, Flux, or Krea2. Pair it with the wrong base model and your output gets wrecked — now you can verify in seconds.2. Catch "lying" filenames. A file can be NAMED sdxl and be anything else. Metadata can't lie — it was written by the trainer at creation time.3. Read the training history. ss_network_dim (rank), ss_network_alpha, learning rate, epochs — it's all recorded. Perfect for comparing two training runs of the same concept.4. Instantly inspect community files. Grabbed a LoRA from a friend or a Discord? One command tells you what's inside.5. Foundation for automation. This 30-line script scales up: scan your entire LoRA folder and generate a spreadsheet of every base model you own (leave it as an exercise — or wait for part 2 😉).🧩 BONUS: DISSECTING LORA KEYSEver wondered why some keys read lora_unet_... and others lora_te_...? Try this:from collections import Counterprefix = Counter(k.split("_")[1] for k in hdr if k.startswith("lora_"))print("Distribution:", dict(prefix))unet = weights for the image model; te1/te2 (text encoders) = weights for prompt understanding. If a LoRA only contains text-encoder weights, it won't change the visual style much.⚠️ LIMITATIONS- This reads structure + metadata, not the weight values. To inspect actual tensors (e.g., hunting NaNs), you'll need the safetensors library or PyTorch.- Metadata is written by the trainer — if the file has been re-merged or baked since, metadata may be altered or missing.🎁 WRAPPING UPsafetensors is an honest format: what you see in the header is what's in the file. With 30 lines of standard-library Python, you can peek inside any model file — fast, safe, and with nothing to install.Compatibility NoteThis Python script is designed for local ComfyUI installations and terminal environments. It requires access to the local filesystem to read ".safetensors" files. TensorArt Cloud ComfyUI may not support this workflow because of its sandbox restrictions.If you use TensorArt's cloud environment, check its available tools and supported workflow features before attempting to run the script.Comment if you want PART 2: a folder scanner that turns all your LoRAs into a tidy spreadsheet (base model, rank, dtype, size) — automatically! 🚀
8
1