File size: 3,326 Bytes
1b24eb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import streamlit as st
import requests
import json

# Digi-Key API and credentials
TOKEN_URL = "https://api.digikey.com/v1/oauth2/token"
API_URL = "https://api.digikey.com/products/v4/search/keyword"
CLIENT_ID = "K9d4a2AaGwQcoAvdNDZVYEOB3sqL4bMg"  # Replace with your Digi-Key Client ID
CLIENT_SECRET = "NxzuxY67eJssGDkA"  # Replace with your Digi-Key Client Secret

# Function to fetch access token
@st.cache_data(ttl=3500)  # Cache the token for its lifespan (1 hour)
def fetch_access_token() -> str:
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
    }
    data = {
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "grant_type": "client_credentials",
    }
    response = requests.post(TOKEN_URL, headers=headers, data=data)
    if response.status_code == 200:
        token_data = response.json()
        return token_data["access_token"]
    else:
        st.error(f"Failed to retrieve access token: {response.status_code} - {response.text}")
        st.stop()

# Function to make API requests to Digi-Key
def search_digikey_components(keywords: str) -> dict:
    access_token = fetch_access_token()  # Get the token automatically
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json",
        "X-DIGIKEY-Client-Id": CLIENT_ID,
    }
    payload = {
        "Keywords": keywords,
        "Limit": 10,
        "Offset": 0,
        "FilterOptionsRequest": {
            "MarketPlaceFilter": "NoFilter",
        },
        "SortOptions": {
            "Field": "None",
            "SortOrder": "Ascending",
        },
    }
    response = requests.post(API_URL, headers=headers, json=payload)
    if response.status_code == 200:
        return response.json()
    else:
        st.error(f"API request failed: {response.status_code} - {response.text}")
        return {}

# Streamlit app interface
st.title("Digi-Key Circuit Component Advisor")
st.write(
    """
    This app helps circuit designers search for electronic components using the Digi-Key API. 
    Enter the name of the component you are looking for to get detailed specifications and associated information.
    """
)

# Input for the user
keywords = st.text_input("Enter the name or keyword of the component:", "")

if keywords:
    st.write(f"Searching for components matching: `{keywords}`...")
    data = search_digikey_components(keywords)
    
    if "Products" in data and data["Products"]:
        st.header("Search Results")
        
        for product in data["Products"]:
            st.subheader(product["Description"]["ProductDescription"])
            st.write(f"**Manufacturer**: {product['Manufacturer']['Name']}")
            st.write(f"**Product Number**: {product['ManufacturerProductNumber']}")
            st.write(f"**Unit Price**: ${product['UnitPrice']}")
            st.write(f"[Datasheet]({product['DatasheetUrl']})")
            st.write(f"[Product Link]({product['ProductUrl']})")

            # Check if PhotoUrl exists and is not None
            if product.get("PhotoUrl"):
                st.image(product["PhotoUrl"], width=200)
            else:
                st.write("_Image not available_")

            st.write("---")
    else:
        st.warning("No components found. Try using different keywords.")