Nawal20 commited on
Commit
1b24eb3
·
verified ·
1 Parent(s): c2a205f

Rename app2.py to app.py

Browse files
Files changed (2) hide show
  1. app.py +92 -0
  2. app2.py +0 -79
app.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ import json
4
+
5
+ # Digi-Key API and credentials
6
+ TOKEN_URL = "https://api.digikey.com/v1/oauth2/token"
7
+ API_URL = "https://api.digikey.com/products/v4/search/keyword"
8
+ CLIENT_ID = "K9d4a2AaGwQcoAvdNDZVYEOB3sqL4bMg" # Replace with your Digi-Key Client ID
9
+ CLIENT_SECRET = "NxzuxY67eJssGDkA" # Replace with your Digi-Key Client Secret
10
+
11
+ # Function to fetch access token
12
+ @st.cache_data(ttl=3500) # Cache the token for its lifespan (1 hour)
13
+ def fetch_access_token() -> str:
14
+ headers = {
15
+ "Content-Type": "application/x-www-form-urlencoded",
16
+ }
17
+ data = {
18
+ "client_id": CLIENT_ID,
19
+ "client_secret": CLIENT_SECRET,
20
+ "grant_type": "client_credentials",
21
+ }
22
+ response = requests.post(TOKEN_URL, headers=headers, data=data)
23
+ if response.status_code == 200:
24
+ token_data = response.json()
25
+ return token_data["access_token"]
26
+ else:
27
+ st.error(f"Failed to retrieve access token: {response.status_code} - {response.text}")
28
+ st.stop()
29
+
30
+ # Function to make API requests to Digi-Key
31
+ def search_digikey_components(keywords: str) -> dict:
32
+ access_token = fetch_access_token() # Get the token automatically
33
+ headers = {
34
+ "Authorization": f"Bearer {access_token}",
35
+ "Content-Type": "application/json",
36
+ "X-DIGIKEY-Client-Id": CLIENT_ID,
37
+ }
38
+ payload = {
39
+ "Keywords": keywords,
40
+ "Limit": 10,
41
+ "Offset": 0,
42
+ "FilterOptionsRequest": {
43
+ "MarketPlaceFilter": "NoFilter",
44
+ },
45
+ "SortOptions": {
46
+ "Field": "None",
47
+ "SortOrder": "Ascending",
48
+ },
49
+ }
50
+ response = requests.post(API_URL, headers=headers, json=payload)
51
+ if response.status_code == 200:
52
+ return response.json()
53
+ else:
54
+ st.error(f"API request failed: {response.status_code} - {response.text}")
55
+ return {}
56
+
57
+ # Streamlit app interface
58
+ st.title("Digi-Key Circuit Component Advisor")
59
+ st.write(
60
+ """
61
+ This app helps circuit designers search for electronic components using the Digi-Key API.
62
+ Enter the name of the component you are looking for to get detailed specifications and associated information.
63
+ """
64
+ )
65
+
66
+ # Input for the user
67
+ keywords = st.text_input("Enter the name or keyword of the component:", "")
68
+
69
+ if keywords:
70
+ st.write(f"Searching for components matching: `{keywords}`...")
71
+ data = search_digikey_components(keywords)
72
+
73
+ if "Products" in data and data["Products"]:
74
+ st.header("Search Results")
75
+
76
+ for product in data["Products"]:
77
+ st.subheader(product["Description"]["ProductDescription"])
78
+ st.write(f"**Manufacturer**: {product['Manufacturer']['Name']}")
79
+ st.write(f"**Product Number**: {product['ManufacturerProductNumber']}")
80
+ st.write(f"**Unit Price**: ${product['UnitPrice']}")
81
+ st.write(f"[Datasheet]({product['DatasheetUrl']})")
82
+ st.write(f"[Product Link]({product['ProductUrl']})")
83
+
84
+ # Check if PhotoUrl exists and is not None
85
+ if product.get("PhotoUrl"):
86
+ st.image(product["PhotoUrl"], width=200)
87
+ else:
88
+ st.write("_Image not available_")
89
+
90
+ st.write("---")
91
+ else:
92
+ st.warning("No components found. Try using different keywords.")
app2.py DELETED
@@ -1,79 +0,0 @@
1
- import os
2
- import requests
3
- import streamlit as st
4
-
5
- # Mouser API credentials
6
- MOUSER_API_KEY = os.getenv('MOUSER_API_KEY')
7
- MOUSER_SEARCH_URL = 'https://api.mouser.com/api/v2/search/keyword'
8
-
9
- if not MOUSER_API_KEY:
10
- st.error("API key not found! Please set 'MOUSER_API_KEY' as an environment variable.")
11
-
12
- # Function to search for components based on a keyword
13
- def fetch_component_data(query):
14
- headers = {
15
- 'Content-Type': 'application/json',
16
- 'Authorization': f'Bearer {MOUSER_API_KEY}'
17
- }
18
- payload = {
19
- 'SearchByKeywordRequest': {
20
- 'keyword': query,
21
- 'records': 10, # Number of results to fetch
22
- 'startingRecord': 0, # Starting record for pagination
23
- 'searchOptions': 'string', # Optional search option
24
- 'searchWithYourSignUpLanguage': 'string' # Optional language
25
- }
26
- }
27
- try:
28
- # Corrected URL format in the f-string
29
- response = requests.post(MOUSER_SEARCH_URL, headers=headers, json=payload)
30
- response.raise_for_status() # Raise error for bad responses (e.g., 404, 500)
31
-
32
- # Debugging: Check if the response is valid
33
- st.write(f"Response received: {response.json()}")
34
-
35
- return response.json()
36
- except requests.exceptions.RequestException as e:
37
- st.error(f"Error fetching data: {e}")
38
- return {}
39
-
40
- # Streamlit Interface
41
- st.title("Component Selection Advisor - Mouser Edition")
42
- st.write("Enter your component requirements (e.g., '10k ohm resistor')")
43
-
44
- # User input
45
- user_query = st.text_input("Enter component name or specification:")
46
-
47
- if st.button("Search"):
48
- if not MOUSER_API_KEY:
49
- st.error("API key is not set! Unable to proceed.")
50
- elif user_query:
51
- st.write(f"Searching for: {user_query}...")
52
-
53
- # Fetch the component data from Mouser API
54
- data = fetch_component_data(user_query)
55
-
56
- if data:
57
- # Check if there are any errors in the response
58
- errors = data.get('Errors', [])
59
- if errors:
60
- st.error(f"Error from API: {errors[0].get('Message', 'Unknown error')}")
61
- st.write("Please try again.")
62
- else:
63
- # Get parts from the response
64
- parts = data.get('SearchResults', {}).get('Parts', [])
65
- if parts:
66
- st.write(f"**Results for '{user_query}':**")
67
- for idx, part in enumerate(parts):
68
- st.write(f"**{idx + 1}. Part Number**: {part.get('MouserPartNumber', 'N/A')}")
69
- st.write(f"**Description**: {part.get('Description', 'N/A')}")
70
- st.write(f"**Manufacturer**: {part.get('Manufacturer', 'N/A')}")
71
- st.write(f"**Availability**: {part.get('Availability', 'N/A')}")
72
- st.write(f"**Product Detail URL**: [Link]({part.get('ProductDetailUrl', '#')})")
73
- st.write("---")
74
- else:
75
- st.write("No components found for your query.")
76
- else:
77
- st.write("Failed to fetch data. Please try again.")
78
- else:
79
- st.warning("Please enter a component specification.")