Untitled
unknown
plain_text
9 months ago
2.2 kB
9
Indexable
# .env
HUGGINGFACE_READ_TOKEN=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
HUGGINGFACE_WRITE_TOKEN=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
import os
from decouple import config
from huggingface_hub import login
from cryptography.fernet import Fernet
# Optional: Encryption setup (only if you want to encrypt/decrypt tokens)
def generate_key():
"""Generate a key for encryption (run once and store securely)."""
key = Fernet.generate_key()
with open("secret.key", "wb") as key_file:
key_file.write(key)
return key
def load_key():
"""Load the encryption key."""
return open("secret.key", "rb").read()
def encrypt_token(token, key):
"""Encrypt a token."""
fernet = Fernet(key)
return fernet.encrypt(token.encode())
def decrypt_token(encrypted_token, key):
"""Decrypt a token."""
fernet = Fernet(key)
return fernet.decrypt(encrypted_token).decode()
# Read tokens from .env
try:
# Read tokens directly from .env (secure if .env is not committed to Git)
access_token_read = config("HUGGINGFACE_READ_TOKEN")
access_token_write = config("HUGGINGFACE_WRITE_TOKEN")
# Optional: Encrypt tokens (if you want an extra layer of security)
key = load_key()
encrypted_read_token = encrypt_token(access_token_read, key)
encrypted_write_token = encrypt_token(access_token_write, key)
# Decrypt tokens when needed
decrypted_read_token = decrypt_token(encrypted_read_token, key)
decrypted_write_token = decrypt_token(encrypted_write_token, key)
# Login to Hugging Face Hub
login(token=decrypted_read_token)
print("Logged in to Hugging Face Hub successfully.")
except Exception as e:
print(f"Error handling Hugging Face tokens: {str(e)}")
import os
from huggingface_hub import login
# Read from environment variables
access_token_read = os.getenv("HUGGINGFACE_READ_TOKEN")
access_token_write = os.getenv("HUGGINGFACE_WRITE_TOKEN")
if access_token_read:
login(token=access_token_read)
else:
raise ValueError("Hugging Face token not found in environment variables.")Editor is loading...
Leave a Comment