Spaces:
Sleeping
Sleeping
compare to chicory-ui
Browse files- chicory_api.py +46 -0
chicory_api.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import json
|
| 3 |
+
from typing import List, Dict, Any
|
| 4 |
+
|
| 5 |
+
def call_chicory_parser(product_names: List[str]) -> Dict[str, Any]:
|
| 6 |
+
"""
|
| 7 |
+
Call the Chicory Parser V3 API to get ingredient predictions
|
| 8 |
+
|
| 9 |
+
Args:
|
| 10 |
+
product_names: List of product names to parse
|
| 11 |
+
|
| 12 |
+
Returns:
|
| 13 |
+
Dictionary mapping product names to their Chicory Parser results
|
| 14 |
+
"""
|
| 15 |
+
url = "https://prod-parserv3.chicoryapp.com/api/v3/prediction"
|
| 16 |
+
|
| 17 |
+
# Prepare the payload
|
| 18 |
+
items = [{"id": i, "text": name} for i, name in enumerate(product_names)]
|
| 19 |
+
payload = json.dumps({"items": items})
|
| 20 |
+
|
| 21 |
+
# Set headers
|
| 22 |
+
headers = {
|
| 23 |
+
'Content-Type': 'application/json'
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
response = requests.post(url, headers=headers, data=payload)
|
| 28 |
+
response.raise_for_status() # Raise exception for HTTP errors
|
| 29 |
+
|
| 30 |
+
# Parse the response
|
| 31 |
+
results = response.json()
|
| 32 |
+
|
| 33 |
+
# Create a dictionary mapping product names to results
|
| 34 |
+
product_results = {}
|
| 35 |
+
for result in results:
|
| 36 |
+
product_name = result["input_text"]
|
| 37 |
+
product_results[product_name] = result
|
| 38 |
+
|
| 39 |
+
return product_results
|
| 40 |
+
|
| 41 |
+
except requests.exceptions.RequestException as e:
|
| 42 |
+
print(f"Error calling Chicory Parser API: {e}")
|
| 43 |
+
return {}
|
| 44 |
+
except json.JSONDecodeError:
|
| 45 |
+
print(f"Error parsing Chicory API response: {response.text}")
|
| 46 |
+
return {}
|