test_plate_json.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import os
  2. import paramiko
  3. import dotenv
  4. repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  5. dotenv.load_dotenv(dotenv_path=os.path.join(repo_root, ".env"))
  6. host = os.environ.get('SERVER_HOST')
  7. user = os.environ.get('SERVER_USER')
  8. password = os.environ.get('SERVER_PASS')
  9. if password == "your_db_password_here" or not password:
  10. password = None
  11. ssh = paramiko.SSHClient()
  12. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  13. try:
  14. ssh.connect(host, username=user, password=password, timeout=10)
  15. print("SSH Connected!")
  16. python_cmd = """
  17. import ollama
  18. import json
  19. model = 'llama3.2:3b'
  20. unique_aliments = [
  21. "peanut butter honey biscuits with peanut butter filling",
  22. "1% milk fat low fat milk",
  23. "peanut butter",
  24. "honey",
  25. "biscuits",
  26. "peanut",
  27. "butter",
  28. "filling",
  29. "1%",
  30. "milk",
  31. "fat",
  32. "low"
  33. ]
  34. aliments_str = ", ".join(unique_aliments)
  35. prompt = f"In these aliments : {aliments_str} are there allergens and if it is the case also said the allergen kinds. Return the answer as json array with two variables aliment and the associate allergen in an array find inside it. focus on the list, do not add or delete aliments."
  36. try:
  37. response = ollama.chat(
  38. model=model,
  39. messages=[{'role': 'user', 'content': prompt}],
  40. format='json'
  41. )
  42. res_content = response['message']['content'].strip()
  43. print("Response Content:\\n", res_content)
  44. data = json.loads(res_content)
  45. # Robust dictionary-or-list JSON parser
  46. aliments_array = []
  47. if isinstance(data, list):
  48. aliments_array = data
  49. elif isinstance(data, dict):
  50. for val in data.values():
  51. if isinstance(val, list):
  52. aliments_array = val
  53. break
  54. table_data = []
  55. if aliments_array:
  56. for entry in aliments_array:
  57. if isinstance(entry, dict):
  58. aliment = entry.get('aliment')
  59. allergens = entry.get('allergen') or entry.get('allergens') or []
  60. if aliment:
  61. if isinstance(allergens, list) and allergens:
  62. cleaned_algs = [str(alg).strip().title() for alg in allergens if alg]
  63. table_data.append({
  64. "Aliment (Ingredient)": aliment.strip().title(),
  65. "Allergen Kind(s)": ", ".join(cleaned_algs)
  66. })
  67. elif isinstance(allergens, str) and allergens.strip():
  68. table_data.append({
  69. "Aliment (Ingredient)": aliment.strip().title(),
  70. "Allergen Kind(s)": allergens.strip().title()
  71. })
  72. print("Table Data:\\n", table_data)
  73. except Exception as e:
  74. print("Error:", e)
  75. """
  76. sftp = ssh.open_sftp()
  77. with sftp.file('food_project/test_plate_json.py', 'w') as f:
  78. f.write(python_cmd)
  79. sftp.close()
  80. ssh.exec_command("docker cp food_project/test_plate_json.py food_project-app-1:/app/test_plate_json.py")
  81. stdin, stdout, stderr = ssh.exec_command("docker exec food_project-app-1 python /app/test_plate_json.py")
  82. print("STDOUT:\n", stdout.read().decode('utf-8'))
  83. print("STDERR:\n", stderr.read().decode('utf-8'))
  84. except Exception as e:
  85. print(f"Error: {e}")
  86. finally:
  87. ssh.close()