from make_website import populate_template_str, datetime, get_json, review_id PESTO_TYPES = ('Genovese', 'Calabrese', 'Arrabiata', 'Herbal', 'Ricotta', 'Rosso', 'Verde') CONSISTENCY_TYPES = ("Creamy", "Rustic") with open('web/templates/table.html', 'r') as f: TABLE_TEMPLATE = f.read() def generate_table_row(review: dict) -> str: """ Brand Name Type Rating Taste Consistency Ingredients Weight Price Servings Serving Price Value * Creamy / Rustic """ return ("" + ("{}" * 13) + "").format( review['company'], make_link( review['name'] + (' ({})'.format(review['variant']) if review['variant'] else ''), './#' + review_id(review) ), get_type_from_categories(review), review['final_verdict']['string'], review['rating_value']['taste'], review['rating_value']['consistency'], review['rating_value']['ingredients'], review['rating_value']['size'], review['rating_value']['price'], review['rating_value']['servings'], price_per_serving(review), taste_grams_per_price(review), ", ".join(cat for cat in review['category'] if cat in CONSISTENCY_TYPES) ) def make_link(name, url): return '{}'.format( url, name ) def get_type_from_categories(review: dict) -> str: cats = review['category'] for name in PESTO_TYPES: if name in cats: return name def price_per_serving(review: dict, raw=False): servings = review['rating_value'].get('servings_value', None) price = review['rating_value'].get('price_value', None) if None in (servings, price): return "???" if isinstance(servings, list): # average number of servings servings = sum(servings) / len(servings) if raw: return price / servings return "{:.2f}€".format(price / servings) def taste_grams_per_price(review): price_per_serving_val = price_per_serving(review, True) if price_per_serving_val == '???': return '???' return "{:.1f}".format( review['rating_value']['taste_percent']**2 / price_per_serving_val * 10 ) if __name__ == '__main__': reviews = get_json()['reviews'] html = populate_template_str( TABLE_TEMPLATE, { 'table_rows': "\n".join(generate_table_row(review) for review in reviews), 'current_year': str(datetime.datetime.now().year) } ) with open("web/table.html", 'w') as f: f.write(html)