Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product Scanner</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f9f9f9;
color: #333;
}
h1 {
text-align: center;
}
.scanner {
text-align: center;
margin-top: 20px;
}
#barcode-input {
width: 300px;
padding: 10px;
font-size: 16px;
}
button {
padding: 10px 20px;
font-size: 16px;
margin-left: 10px;
cursor: pointer;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
}
button:hover {
background-color: #0056b3;
}
#results {
margin-top: 20px;
}
.risk {
color: red;
}
</style>
</head>
<body>
<h1>Product Scanner</h1>
<div class="scanner">
<input type="text" id="barcode-input" placeholder="Enter barcode">
<button id="scan-btn">Scan</button>
</div>
<div id="results"></div>

<script>
const scanButton = document.getElementById('scan-btn');
const barcodeInput = document.getElementById('barcode-input');
const resultsDiv = document.getElementById('results');

scanButton.addEventListener('click', async () => {
const barcode = barcodeInput.value.trim();

if (!barcode) {
resultsDiv.innerHTML = `<p class="risk">Please enter a barcode.</p>`;
return;
}

resultsDiv.innerHTML = `<p>Loading...</p>`;

try {
// Fetch product and risk analysis data from the updated API URL
const response = await fetch('https://164fe496-83fc-4631-b639-1cda16ae14cd-00-18s1mcjmf3xgv.spock.replit.dev/scan', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
barcode: barcode
}),
});

if (!response.ok) {
const error = await response.json();
resultsDiv.innerHTML = `<p class="risk">Error: ${error.error}</p>`;
return;
}

const data = await response.json();

// Display the product and risk information
resultsDiv.innerHTML = `
<h2>Product: ${data.product_name || 'Unknown'}</h2>
<h3>Ingredients:</h3>
<ul>
${data.ingredients ? data.ingredients.map(ingredient => `<li>${ingredient}</li>`).join('') : '<li>No ingredients available.</li>'}
</ul>
<h3>Risks:</h3>
${data.risks && data.risks.length > 0
? `<ul>${data.risks.map(risk => `<li class="risk"><strong>${risk.ingredient}:</strong> ${risk.risk}</li>`).join('')}</ul>`
: '<p>No risky ingredients found.</p>'
}
`;
} catch (error) {
resultsDiv.innerHTML = `<p class="risk">An error occurred: ${error.message}</p>`;
}
});
</script>
</body>
</html>
102 changes: 50 additions & 52 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,90 +1,88 @@
from flask import Flask, request, jsonify
import requests
import os
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

# Simulated database of risky ingredients
RISKY_INGREDIENTS = {
"aspartame": "May cause allergic reactions and has potential brain effects.",
"BHA": "Potential carcinogen linked to liver and kidney damage.",
"BHT": "Potential carcinogen that can alter metabolism.",
"acrylamide": "Classified as a carcinogen, linked to increased cancer risk.",
"monosodium glutamate": "Can cause headaches and other adverse reactions.",
"salt": "Excessive consumption of salt can lead to high blood pressure, increased risk of heart disease, stroke, kidney disease, and headaches due to dehydration."

}

# Endpoint to get product information via barcode
def get_product_data(barcode):
url = f"https://world.openfoodfacts.org/api/v0/product/{barcode}.json"

try:
response = requests.get(url, timeout=5)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
raise Exception(f"Failed to fetch product data: {str(e)}")

@app.route('/scan', methods=['POST'])
def scan_barcode():
data = request.get_json()
if not data or 'barcode' not in data:
return jsonify({"error": "Barcode is required"}), 400

barcode = data['barcode']
url = f"https://world.openfoodfacts.org/api/v0/product/{barcode}.json"

# Call Open Food Facts API
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # Check for HTTP errors
except requests.exceptions.RequestException as e:
return jsonify({"error": f"Failed to fetch product data: {str(e)}"}), 500
product_data = get_product_data(barcode)

product_data = response.json()
if product_data.get('status') != 1:
return jsonify({"error": "Product not found"}), 404
if product_data.get('status') != 1:
return jsonify({"error": "Product not found"}), 404

product = product_data['product']
result = {
"product_name": product.get("product_name", "Unknown"),
"ingredients": [i.get('text', '').lower() for i in product.get("ingredients", [])],
"nutritional_info": product.get("nutriments", {})
}
return jsonify(result), 200
product = product_data['product']
result = {
"product_name": product.get("product_name", "Unknown"),
"ingredients": [i.get('text', '').lower() for i in product.get("ingredients", [])],
"nutritional_info": product.get("nutriments", {})
}
return jsonify(result), 200
except Exception as e:
return jsonify({"error": str(e)}), 500

# New endpoint to analyze ingredients starting from barcode
@app.route('/analyze', methods=['POST'])
def analyze_ingredients():
data = request.get_json()
if not data or 'barcode' not in data:
return jsonify({"error": "Barcode is required"}), 400

barcode = data['barcode']
url = f"https://world.openfoodfacts.org/api/v0/product/{barcode}.json"

# Call Open Food Facts API to get the product data
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # Check for HTTP errors
except requests.exceptions.RequestException as e:
return jsonify({"error": f"Failed to fetch product data: {str(e)}"}), 500

product_data = response.json()
if product_data.get('status') != 1:
return jsonify({"error": "Product not found"}), 404

product = product_data['product']
ingredients = [i.get('text', '').lower() for i in product.get("ingredients", [])]

# Analyze the ingredients against the risky ingredients list
risks = []
for ingredient in ingredients:
if ingredient in RISKY_INGREDIENTS:
risks.append({
"ingredient": ingredient,
"risk": RISKY_INGREDIENTS[ingredient]
})

# Return the analysis result
return jsonify({
"product_name": product.get("product_name", "Unknown"),
"ingredients": ingredients,
"risks": risks
}), 200

# Start the server on 0.0.0.0 and dynamic port
product_data = get_product_data(barcode)

if product_data.get('status') != 1:
return jsonify({"error": "Product not found"}), 404

product = product_data['product']
ingredients = [i.get('text', '').lower() for i in product.get("ingredients", [])]

risks = []
for ingredient in ingredients:
if ingredient in RISKY_INGREDIENTS:
risks.append({
"ingredient": ingredient,
"risk": RISKY_INGREDIENTS[ingredient]
})

return jsonify({
"product_name": product.get("product_name", "Unknown"),
"ingredients": ingredients,
"risks": risks
}), 200

except Exception as e:
return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000)) # Use the dynamic port provided by Replit or default to 5000
port = int(os.environ.get('PORT', 5000)) # Usa la porta dinamica di Replit, o la porta 5000 come predefinita
app.run(host='0.0.0.0', port=port, debug=True)