thechaiexperiment commited on
Commit
28f8ba5
·
1 Parent(s): de5f21f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -15
app.py CHANGED
@@ -633,31 +633,71 @@ async def resources_endpoint(profile: MedicalProfile):
633
  @app.post("/api/recipes")
634
  async def recipes_endpoint(profile: MedicalProfile):
635
  try:
636
- recipe_query = f"Recipes and meals suitable for someone with: {', '.join(profile.chronic_conditions + profile.food_restrictions)}"
637
- query_text = recipe_query
638
- query_embedding = embed_query_text(query_text) # Embed the query text
639
- embeddings_data = load_embeddings ()
 
 
 
 
 
 
 
 
 
 
640
  folder_path = 'downloaded_articles/downloaded_articles'
641
  initial_results = query_embeddings(query_embedding, embeddings_data, n_results=5)
 
 
 
 
642
  document_ids = [doc_id for doc_id, _ in initial_results]
 
 
643
  document_texts = retrieve_document_texts(document_ids, folder_path)
 
 
 
 
644
  cross_encoder = models['cross_encoder']
645
  scores = cross_encoder.predict([(query_text, doc) for doc in document_texts])
 
 
 
646
  scored_documents = list(zip(scores, document_ids, document_texts))
647
- ranked_docs = scored_documents.sort(key=lambda x: x[0], reverse=True)
 
 
 
 
 
 
648
  recipes = []
649
- for (doc_id, _), score, text in ranked_docs[:10]:
650
- doc_info = data['df'][data['df']['id'] == doc_id].iloc[0]
651
- if 'recipe' in text.lower() or 'meal' in text.lower():
652
- recipes.append({
653
- "id": doc_id,
654
- "title": doc_info['title'],
655
- "content": text[:200],
656
- "score": float(score)
657
- })
 
 
 
 
 
658
  return {"recipes": recipes[:5], "success": True}
 
 
 
 
659
  except Exception as e:
660
- raise HTTPException(status_code=500, detail=str(e))
 
 
661
 
662
  if not init_success:
663
  print("Warning: Application initialized with partial functionality")
 
633
  @app.post("/api/recipes")
634
  async def recipes_endpoint(profile: MedicalProfile):
635
  try:
636
+ # Build the query text for recipes
637
+ recipe_query = (
638
+ f"Recipes and meals suitable for someone with: "
639
+ f"{profile.conditions} and experiencing {profile.daily_symptoms}"
640
+ )
641
+ query_text = recipe_query
642
+
643
+ # Generate the query embedding
644
+ query_embedding = embed_query_text(query_text)
645
+ if query_embedding is None:
646
+ raise ValueError("Failed to generate query embedding.")
647
+
648
+ # Load embeddings and retrieve initial results
649
+ embeddings_data = load_embeddings()
650
  folder_path = 'downloaded_articles/downloaded_articles'
651
  initial_results = query_embeddings(query_embedding, embeddings_data, n_results=5)
652
+ if not initial_results:
653
+ raise ValueError("No relevant recipes found.")
654
+
655
+ # Extract document IDs
656
  document_ids = [doc_id for doc_id, _ in initial_results]
657
+
658
+ # Retrieve document texts
659
  document_texts = retrieve_document_texts(document_ids, folder_path)
660
+ if not document_texts:
661
+ raise ValueError("Failed to retrieve document texts.")
662
+
663
+ # Perform re-ranking with cross-encoder
664
  cross_encoder = models['cross_encoder']
665
  scores = cross_encoder.predict([(query_text, doc) for doc in document_texts])
666
+ scores = [float(score) for score in scores] # Convert scores to native floats
667
+
668
+ # Combine document data
669
  scored_documents = list(zip(scores, document_ids, document_texts))
670
+ scored_documents.sort(key=lambda x: x[0], reverse=True) # Sort by score
671
+
672
+ # Load recipe metadata from DataFrame
673
+ file_path = 'finalcleaned_excel_file.xlsx'
674
+ df = pd.read_excel(file_path)
675
+
676
+ # Prepare the final recipes list
677
  recipes = []
678
+ for score, doc_id, text in scored_documents:
679
+ # Retrieve metadata for the document
680
+ doc_info = df[df['Unnamed: 0'] == doc_id]
681
+ if not doc_info.empty:
682
+ title = doc_info.iloc[0]['title'] if 'title' in doc_info.columns else "Unknown Title"
683
+ if 'recipe' in text.lower() or 'meal' in text.lower():
684
+ recipes.append({
685
+ "id": doc_id,
686
+ "title": title,
687
+ "content_preview": text[:200], # First 200 characters of text
688
+ "score": score,
689
+ })
690
+
691
+ # Limit the response to top 5 recipes
692
  return {"recipes": recipes[:5], "success": True}
693
+
694
+ except ValueError as ve:
695
+ # Handle expected errors
696
+ raise HTTPException(status_code=400, detail=str(ve))
697
  except Exception as e:
698
+ # Handle unexpected errors
699
+ print(f"Unexpected error: {e}")
700
+ raise HTTPException(status_code=500, detail="An unexpected error occurred.")
701
 
702
  if not init_success:
703
  print("Warning: Application initialized with partial functionality")