import torch def generate_recipe_summary( recipe_texts: list[str], model, processor, max_new_tokens: int = 512 ) -> str: recipes_combined = "" for i, recipe in enumerate(recipe_texts[:3], 1): recipes_combined += f"\n\n--- RECIPE {i} ---\n{recipe}" prompt = f"""You are a helpful culinary assistant. Below are {len(recipe_texts[:3])} recipes. Please provide a brief markdown summary with: - A short 1-2 sentence overview of each recipe - Key ingredients highlighted - Estimated difficulty (Easy/Medium/Hard) - Which recipe might be best for a quick weeknight dinner For example use the following format: ```markdown # Recipe summary ## [details] ``` Keep the summary concise and well-formatted in markdown. Return in ```markdown``` tags so it can be easily parsed. {recipes_combined} ## Summary:""" messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}] inputs = processor.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt" ) inputs = inputs.to(model.device) with torch.no_grad(): generated_ids = model.generate( **inputs, max_new_tokens=max_new_tokens, do_sample=True, temperature=0.7, top_p=0.9 ) generated_ids_trimmed = [ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) ] output_text = processor.batch_decode( generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False )[0] return output_text.strip() def _markdown_to_simple_html(markdown_text: str, max_reviews: int = 1) -> str: lines = markdown_text.strip().split('\n') title = "" description = "" recipe_id = "" cook_time = "" num_ratings = "" ingredients = [] steps = [] tags = [] reviews = [] current_section = None in_ingredients = False in_steps = False in_reviews = False in_tags = False review_count = 0 for line in lines: line = line.strip() if line.startswith('# ') and not title: title = line[2:].strip() continue if line.startswith('**ID:**'): recipe_id = line.replace('**ID:**', '').strip() continue if line.startswith('**Time:**'): cook_time = line.replace('**Time:**', '').strip() continue if line.startswith('**Number of Ratings:**'): num_ratings = line.replace('**Number of Ratings:**', '').strip() continue if line.startswith('## '): section_name = line[3:].strip().lower() in_ingredients = section_name == 'ingredients' in_steps = section_name.startswith('steps') in_reviews = section_name == 'reviews' in_tags = section_name == 'tags' current_section = section_name continue if current_section == 'description' and line and not line.startswith('#'): description = line continue if in_ingredients and line.startswith('- '): ingredients.append(line[2:].strip()) continue if in_steps and line and line[0].isdigit(): step_text = line.split('. ', 1)[-1] if '. ' in line else line steps.append(step_text.strip()) continue if in_tags and line.startswith('`'): tag_list = [t.strip().strip('`') for t in line.split(',')] tags.extend(tag_list) continue if in_reviews and line.startswith('> ') and review_count < max_reviews: reviews.append(line[2:].strip()) review_count += 1 continue html = f'''
{title}
{f'⏱️ {cook_time}' if cook_time else ''} {f'⭐ {num_ratings} ratings' if num_ratings else ''} {f'ID: {recipe_id}' if recipe_id else ''}
{description[:150]}{"..." if len(description) > 150 else ""}
📝 Ingredients
{", ".join(ingredients[:8])}{"..." if len(ingredients) > 8 else ""}
👨‍🍳 Steps ({len(steps)} total)
    {"".join(f'
  1. {step[:80]}{"..." if len(step) > 80 else ""}
  2. ' for step in steps[:4])} {f'
  3. ...and {len(steps) - 4} more steps
  4. ' if len(steps) > 4 else ''}
''' if tags: display_tags = tags[:5] html += f'''
🏷️ Tags
{"".join(f'{tag}' for tag in display_tags)} {f'+{len(tags) - 5} more' if len(tags) > 5 else ''}
''' if reviews: html += f'''
💬 Review
"{reviews[0][:200]}{"..." if len(reviews[0]) > 200 else ""}"
''' html += '
' return html def create_recipe_cards_html(scores_and_samples: list[dict], num_results: int = 3) -> str: recipe_cards_html = [] for item in scores_and_samples[:num_results]: sample = item["sample"] markdown_text = sample.get("recipe_markdown", "") card_html = _markdown_to_simple_html(markdown_text) recipe_cards_html.append(f'
{card_html}
') combined_html = f'''

Retrieved Texts

{"".join(recipe_cards_html)}
''' return combined_html