Spaces:
Sleeping
Sleeping
Update disease.py
Browse files- disease.py +141 -144
disease.py
CHANGED
|
@@ -1,145 +1,142 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
from flask import Flask, request, jsonify
|
| 4 |
-
import google.generativeai as genai
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
# ---
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
#
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
)
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
"""
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
""
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
return {"
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
"""
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
#
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
)
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
print(
|
| 141 |
-
print("
|
| 142 |
-
else:
|
| 143 |
-
print("Starting Flask server...")
|
| 144 |
-
print(f"Fact sheets loaded for: {', '.join(get_available_diseases())}")
|
| 145 |
app.run(debug=True, port=5001)
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from flask import Flask, request, jsonify
|
| 4 |
+
import google.generativeai as genai
|
| 5 |
+
|
| 6 |
+
# --- Configuration ---
|
| 7 |
+
FACT_SHEET_DIR = "Text_Files"
|
| 8 |
+
|
| 9 |
+
# --- System Instruction for the Gemini Model ---
|
| 10 |
+
# This instruction guides the model's behavior, ensuring it stays on task
|
| 11 |
+
# and uses only the tools and information we provide.
|
| 12 |
+
SYSTEM_INSTRUCTION = """
|
| 13 |
+
You are a helpful Health Fact Sheet Assistant. Your role is to answer questions
|
| 14 |
+
about specific diseases based ONLY on the information contained in the fact sheets
|
| 15 |
+
provided to you through the get_disease_fact_sheet tool.
|
| 16 |
+
Generate response in same language as user query.
|
| 17 |
+
|
| 18 |
+
Follow these rules strictly:
|
| 19 |
+
1. Use the fact sheet for answers whenever possible.
|
| 20 |
+
2. To get information, call the get_disease_fact_sheet function.
|
| 21 |
+
3. If the fact sheet doesn't cover the answer, reply using general knowledge and include a disclaimer.
|
| 22 |
+
4. First, check the user's query to see which disease it refers to, then fetch that fact sheet.
|
| 23 |
+
5. If the query isn't about a specific disease, reply using general knowledge with a disclaimer.
|
| 24 |
+
6. Keep responses clear, short, and simple. Don't mention the source of the information.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
# Configure the Google Generative AI SDK.
|
| 28 |
+
try:
|
| 29 |
+
# This will automatically look for the GOOGLE_API_KEY environment variable.
|
| 30 |
+
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
| 31 |
+
|
| 32 |
+
# Initialize the Gemini model with the system instruction.
|
| 33 |
+
# We recommend using a model that is highly optimized for tool use.
|
| 34 |
+
model = genai.GenerativeModel(
|
| 35 |
+
'gemini-1.5-flash',
|
| 36 |
+
system_instruction=SYSTEM_INSTRUCTION
|
| 37 |
+
)
|
| 38 |
+
except Exception as e:
|
| 39 |
+
print(f"Error configuring Google Generative AI: {e}")
|
| 40 |
+
print("Please make sure your GOOGLE_API_KEY environment variable is set.")
|
| 41 |
+
model = None
|
| 42 |
+
|
| 43 |
+
# --- Flask App Initialization ---
|
| 44 |
+
app = Flask(__name__)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# --- Helper Functions (Tool Implementation) ---
|
| 48 |
+
|
| 49 |
+
def get_available_diseases():
|
| 50 |
+
"""Scans the directory for available disease fact sheets."""
|
| 51 |
+
if not os.path.isdir(FACT_SHEET_DIR):
|
| 52 |
+
return []
|
| 53 |
+
# Create a clean list of names from filenames (e.g., "Chickenpox_and_Shingles.txt" -> "Chickenpox and Shingles")
|
| 54 |
+
return [os.path.splitext(f)[0].replace('_', ' ') for f in os.listdir(FACT_SHEET_DIR) if f.endswith(".txt")]
|
| 55 |
+
|
| 56 |
+
def get_disease_fact_sheet(disease_name: str):
|
| 57 |
+
"""
|
| 58 |
+
This is the actual Python function that gets executed by the model.
|
| 59 |
+
It reads the content of a specific disease's text file from the local directory.
|
| 60 |
+
"""
|
| 61 |
+
print(f"--- TOOL EXECUTION: Running get_disease_fact_sheet(disease_name='{disease_name}') ---")
|
| 62 |
+
# Convert the friendly name back to a filename format
|
| 63 |
+
filename = disease_name.replace(' ', '_') + ".txt"
|
| 64 |
+
filepath = os.path.join(FACT_SHEET_DIR, filename)
|
| 65 |
+
|
| 66 |
+
if os.path.exists(filepath):
|
| 67 |
+
with open(filepath, 'r', encoding='utf-8') as f:
|
| 68 |
+
content = f.read()
|
| 69 |
+
print(f"--- SUCCESS: Found and read '{filename}' ---")
|
| 70 |
+
# Return a dictionary, which will be implicitly handled by the Gemini SDK
|
| 71 |
+
return {"disease": disease_name, "content": content}
|
| 72 |
+
else:
|
| 73 |
+
print(f"--- ERROR: Fact sheet not found for '{disease_name}' ---")
|
| 74 |
+
return {"error": f"Fact sheet not found for the disease: {disease_name}."}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# --- Main API Endpoint ---
|
| 78 |
+
|
| 79 |
+
@app.route('/ask', methods=['POST'])
|
| 80 |
+
def ask_question():
|
| 81 |
+
"""
|
| 82 |
+
Handles user queries by orchestrating the interaction with the Gemini model,
|
| 83 |
+
which is guided by the system instruction to use the provided tools and context.
|
| 84 |
+
"""
|
| 85 |
+
if not model:
|
| 86 |
+
return jsonify({"error": "Gemini client is not configured. Check your API key."}), 500
|
| 87 |
+
|
| 88 |
+
data = request.get_json()
|
| 89 |
+
if not data or 'query' not in data:
|
| 90 |
+
return jsonify({"error": "Request must be JSON and contain a 'query' field."}), 400
|
| 91 |
+
|
| 92 |
+
user_query = data['query']
|
| 93 |
+
print(f"\n=================================================")
|
| 94 |
+
print(f"Received new query: '{user_query}'")
|
| 95 |
+
print(f"=================================================")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
available_diseases = get_available_diseases()
|
| 99 |
+
if not available_diseases:
|
| 100 |
+
return jsonify({"error": f"No fact sheets found in the '{FACT_SHEET_DIR}' directory."}), 500
|
| 101 |
+
|
| 102 |
+
# === Orchestration with Gemini ===
|
| 103 |
+
try:
|
| 104 |
+
# We start a chat session. The model will automatically handle calling the
|
| 105 |
+
# function and using its output to generate a final answer, thanks to
|
| 106 |
+
# automatic function calling and the system instruction.
|
| 107 |
+
chat = model.start_chat(enable_automatic_function_calling=True)
|
| 108 |
+
|
| 109 |
+
# Construct a more informative prompt for the model.
|
| 110 |
+
prompt = f"""
|
| 111 |
+
Here is the user's question: '{user_query}'
|
| 112 |
+
|
| 113 |
+
Please use your tools to answer it. The available diseases you can look up are:
|
| 114 |
+
{', '.join(available_diseases)}
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
print("--- Sending request to Gemini... ---")
|
| 118 |
+
# Send the user's query and the definitions of the available tools
|
| 119 |
+
response = chat.send_message(
|
| 120 |
+
prompt,
|
| 121 |
+
tools=[get_disease_fact_sheet] # Pass the actual function reference
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
final_answer = response.text
|
| 125 |
+
print(f"--- Gemini's Final Answer: ---\n{final_answer}\n")
|
| 126 |
+
return jsonify({"response": final_answer})
|
| 127 |
+
|
| 128 |
+
except Exception as e:
|
| 129 |
+
print(f"--- An unexpected error occurred: {e} ---")
|
| 130 |
+
return jsonify({"error": f"Gemini API Error: {e}"}), 500
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# --- To run the app ---
|
| 134 |
+
if __name__ == '__main__':
|
| 135 |
+
# Make sure the Text_Files directory exists before starting
|
| 136 |
+
if not os.path.isdir(FACT_SHEET_DIR):
|
| 137 |
+
print(f"CRITICAL ERROR: The directory '{FACT_SHEET_DIR}' does not exist.")
|
| 138 |
+
print("Please create it and populate it with the disease .txt files.")
|
| 139 |
+
else:
|
| 140 |
+
print("Starting Flask server...")
|
| 141 |
+
print(f"Fact sheets loaded for: {', '.join(get_available_diseases())}")
|
|
|
|
|
|
|
|
|
|
| 142 |
app.run(debug=True, port=5001)
|