File size: 2,419 Bytes
65be7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python3
"""Test HF token with modern InferenceClient approach."""

import os

from dotenv import load_dotenv

# Load environment variables
load_dotenv()

def test_hf_token():
    """Test HF token with different approaches."""
    token = os.getenv("HF_TOKEN")
    print(f"Token loaded: {token[:20]}..." if token else "No token found")

    if not token:
        print("❌ No HF_TOKEN found in environment")
        return None

    # Test 1: Modern InferenceClient approach
    print("\nπŸ”„ Testing with InferenceClient (recommended)...")
    try:
        from huggingface_hub import InferenceClient
        client = InferenceClient(token=token)
        result = client.text_classification(
            "I love this product!",
            model="cardiffnlp/twitter-roberta-base-sentiment-latest"
        )
        print("βœ… Success with InferenceClient!")
        print("Result:", result)
        return True
    except Exception as e:
        print("❌ InferenceClient error:", str(e))

    # Test 2: Direct API call (old approach)
    print("\nπŸ”„ Testing with direct API call...")
    try:
        import requests
        headers = {"Authorization": f"Bearer {token}"}
        payload = {"inputs": "I love this product!"}
        response = requests.post(
            "https://api-inference.huggingface.co/models/cardiffnlp/twitter-roberta-base-sentiment-latest",
            headers=headers,
            json=payload,
            timeout=30
        )
        print(f"Status code: {response.status_code}")
        if response.status_code == 200:
            print("βœ… Success with direct API!")
            print("Result:", response.json())
            return True
        print("❌ API error:", response.text)
    except Exception as e:
        print("❌ Direct API error:", str(e))

    # Test 3: Token validation
    print("\nπŸ”„ Testing token validation...")
    try:
        import requests
        headers = {"Authorization": f"Bearer {token}"}
        response = requests.get("https://huggingface.co/api/whoami", headers=headers)
        if response.status_code == 200:
            print("βœ… Token is valid!")
            print("User info:", response.json())
        else:
            print("❌ Token validation failed:", response.text)
    except Exception as e:
        print("❌ Token validation error:", str(e))

    return False

if __name__ == "__main__":
    test_hf_token()