Nawal20 commited on
Commit
3f9e9a0
·
verified ·
1 Parent(s): c368104

Rename app1.py to app.py

Browse files
Files changed (2) hide show
  1. app.py +76 -0
  2. app1.py +0 -144
app.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ import json
4
+
5
+ # Digi-Key API details
6
+ API_URL = "https://api.digikey.com/products/v4/search/keyword"
7
+ API_KEY = "K9d4a2AaGwQcoAvdNDZVYEOB3sqL4bMg" # Replace with your Digi-Key API key
8
+
9
+ # Define a function to make API requests to Digi-Key
10
+ def search_digikey_components(keywords: str) -> dict:
11
+ headers = {
12
+ "Authorization": f"Bearer {API_KEY}",
13
+ "Content-Type": "application/json",
14
+ }
15
+ payload = {
16
+ "Keywords": keywords,
17
+ "Limit": 10,
18
+ "Offset": 0,
19
+ "FilterOptionsRequest": {
20
+ "MarketPlaceFilter": "NoFilter",
21
+ "SearchOptions": ["ChipOutpost"],
22
+ },
23
+ "SortOptions": {
24
+ "Field": "None",
25
+ "SortOrder": "Ascending",
26
+ },
27
+ }
28
+
29
+ # Make the POST request
30
+ response = requests.post(API_URL, headers=headers, json=payload)
31
+
32
+ if response.status_code == 200:
33
+ return response.json()
34
+ else:
35
+ st.error(f"API request failed with status code {response.status_code}: {response.text}")
36
+ return {}
37
+
38
+ # Streamlit app interface
39
+ st.title("Digi-Key Circuit Component Advisor")
40
+ st.write(
41
+ """
42
+ This app helps circuit designers search for electronic components using the Digi-Key API.
43
+ Enter the name of the component you are looking for to get detailed specifications and associated information.
44
+ """
45
+ )
46
+
47
+ # Input for the user
48
+ keywords = st.text_input("Enter the name or keyword of the component:", "")
49
+
50
+ if keywords:
51
+ st.write(f"Searching for components matching: `{keywords}`...")
52
+ data = search_digikey_components(keywords)
53
+
54
+ if "Products" in data and data["Products"]:
55
+ st.header("Search Results")
56
+
57
+ for product in data["Products"]:
58
+ st.subheader(product["Description"]["ProductDescription"])
59
+ st.write(f"**Manufacturer**: {product['Manufacturer']['Name']}")
60
+ st.write(f"**Product Number**: {product['ManufacturerProductNumber']}")
61
+ st.write(f"**Unit Price**: ${product['UnitPrice']}")
62
+ st.write(f"[Datasheet]({product['DatasheetUrl']})")
63
+ st.write(f"[Product Link]({product['ProductUrl']})")
64
+ st.image(product["PhotoUrl"], width=200)
65
+ st.write("---")
66
+ else:
67
+ st.warning("No components found. Try using different keywords.")
68
+
69
+ # Instructions for deployment
70
+ st.write("---")
71
+ st.write(
72
+ "### Deployment Instructions:\n"
73
+ "1. Clone this code and push it to a Hugging Face repository.\n"
74
+ "2. Use the `requirements.txt` file to list dependencies.\n"
75
+ "3. Deploy it on Hugging Face Spaces."
76
+ )
app1.py DELETED
@@ -1,144 +0,0 @@
1
- import os
2
- import requests
3
- import streamlit as st
4
-
5
- # Digi-Key API credentials
6
- CLIENT_ID = os.getenv('DIGIKEY_CLIENT_ID')
7
- CLIENT_SECRET = os.getenv('DIGIKEY_CLIENT_SECRET')
8
- TOKEN_URL = 'https://api.digikey.com/v1/oauth2/token'
9
- API_BASE_URL = 'https://api.digikey.com/products/v4/search'
10
- #API_BASE_URL = 'https://api.mouser.com/api/docs/V1'
11
-
12
- if not CLIENT_ID or not CLIENT_SECRET:
13
- st.error("API credentials not found! Please set 'DIGIKEY_CLIENT_ID' and 'DIGIKEY_CLIENT_SECRET' environment variables.")
14
-
15
- # Function to fetch OAuth2 token
16
- def fetch_access_token():
17
- data = {
18
- 'client_id': CLIENT_ID,
19
- 'client_secret': CLIENT_SECRET,
20
- 'grant_type': 'client_credentials'
21
- }
22
- try:
23
- response = requests.post(TOKEN_URL, data=data)
24
- response.raise_for_status()
25
- token_data = response.json()
26
- return token_data.get('access_token')
27
- except requests.exceptions.RequestException as e:
28
- st.error(f"Error fetching access token: {e}")
29
- return None
30
-
31
- # Function to search for components
32
- def fetch_component_data(query, token):
33
- headers = {
34
- 'Authorization': f'Bearer {token}',
35
- }
36
- params = {
37
- 'keywords': query,
38
- 'limit': 10, # Limit to top 5 results
39
- }
40
- try:
41
- #response = requests.get(f"{API_BASE_URL}/keyword", headers=headers, params=params)
42
- response = requests.get("https://api.digikey.com/products/v4/search/keyword", headers=headers, params=params)
43
- response.raise_for_status()
44
- return response.json()
45
- except requests.exceptions.RequestException as e:
46
- st.error(f"Error fetching data: {e}")
47
- return []
48
-
49
- # Function to get detailed product information
50
- def fetch_product_details(part_number, token):
51
- headers = {
52
- 'Authorization': f'Bearer {token}',
53
- }
54
- params = {
55
- 'partNumber': part_number,
56
- }
57
- try:
58
- response = requests.get(f"{API_BASE_URL}/{productNumber}/productdetails", headers=headers, params=params)
59
- response.raise_for_status()
60
- return response.json()
61
- except requests.exceptions.RequestException as e:
62
- st.error(f"Error fetching product details: {e}")
63
- return {}
64
-
65
- # Function to get product pricing
66
- def fetch_product_pricing(part_number, token):
67
- headers = {
68
- 'Authorization': f'Bearer {token}',
69
- }
70
- params = {
71
- 'partNumber': part_number,
72
- }
73
- try:
74
- response = requests.get(f"{API_BASE_URL}/{productNumber}/pricing", headers=headers, params=params)
75
- response.raise_for_status()
76
- return response.json()
77
- except requests.exceptions.RequestException as e:
78
- st.error(f"Error fetching product pricing: {e}")
79
- return {}
80
-
81
- # Streamlit Interface
82
- st.title("Digi-Key Component Selection Advisor")
83
- st.write("Enter your component requirements (e.g., '10k ohm resistor')")
84
-
85
- # User input
86
- user_query = st.text_input("Enter component name or specification:")
87
-
88
- if st.button("Search"):
89
- if not CLIENT_ID or not CLIENT_SECRET:
90
- st.error("API credentials are not set! Unable to proceed.")
91
- else:
92
- st.write("Authenticating...")
93
- token = fetch_access_token()
94
- if token:
95
- st.write(f"Searching for: {user_query}...")
96
-
97
- # Fetching components based on the keyword search
98
- data = fetch_component_data(user_query, token)
99
-
100
- if data:
101
- st.write(f"**Results for '{user_query}':**")
102
- component_list = data.get('data', [])
103
-
104
- if not component_list:
105
- st.write("No components found for your query.")
106
- else:
107
- for idx, item in enumerate(component_list):
108
- st.write(f"**{idx + 1}. Part Number**: {item['partNumber']}")
109
- st.write(f"**Description**: {item['description']}")
110
- st.write(f"**Manufacturer**: {item['manufacturer']['name']}")
111
- st.write(f"**Stock Available**: {item['availability']['quantity']}")
112
- st.write("---")
113
-
114
- selected_idx = st.number_input("Select a product number (1, 2, 3, etc.):", min_value=1, max_value=len(component_list), step=1)
115
-
116
- if selected_idx:
117
- selected_part = component_list[selected_idx - 1]
118
- part_number = selected_part['partNumber']
119
-
120
- # Fetching detailed product information
121
- product_details = fetch_product_details(part_number, token)
122
- if product_details:
123
- st.write(f"**Detailed Information for Part Number: {part_number}**")
124
- st.write(f"**Description**: {product_details.get('description')}")
125
- st.write(f"**Manufacturer**: {product_details.get('manufacturer', {}).get('name')}")
126
- st.write(f"**Dimensions**: {product_details.get('dimensions', 'N/A')}")
127
- st.write(f"**Availability**: {product_details.get('availability', {}).get('quantity', 'N/A')} in stock")
128
- st.write("---")
129
-
130
- # Fetching pricing information
131
- pricing_details = fetch_product_pricing(part_number, token)
132
- if pricing_details:
133
- st.write(f"**Pricing for Part Number: {part_number}**")
134
- prices = pricing_details.get('pricing', [])
135
- if prices:
136
- for price in prices:
137
- st.write(f"{price['quantity']} units: {price['price']} {price['currency']}")
138
- else:
139
- st.write("Pricing details not available.")
140
- st.write("---")
141
- else:
142
- st.write("No components found for your query.")
143
- else:
144
- st.error("Unable to authenticate with the Digi-Key API.")