Spaces:
Sleeping
Sleeping
Update disease.py
Browse files- disease.py +170 -70
disease.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
from flask import Flask, request, jsonify
|
|
@@ -9,9 +11,7 @@ dotenv.load_dotenv()
|
|
| 9 |
# --- Configuration ---
|
| 10 |
FACT_SHEET_DIR = "Text_Files"
|
| 11 |
|
| 12 |
-
# --- System Instruction
|
| 13 |
-
# This instruction guides the model's behavior, ensuring it stays on task
|
| 14 |
-
# and uses only the tools and information we provide.
|
| 15 |
SYSTEM_INSTRUCTION = """
|
| 16 |
You are a helpful Health Fact Sheet Assistant. Your role is to answer questions
|
| 17 |
about specific diseases based ONLY on the information contained in the fact sheets
|
|
@@ -27,120 +27,220 @@ Follow these rules strictly:
|
|
| 27 |
6. Keep responses clear, short, and simple. Don't mention the source of the information.
|
| 28 |
"""
|
| 29 |
|
| 30 |
-
# Configure
|
| 31 |
try:
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
model = genai.GenerativeModel(
|
| 38 |
-
'gemini-
|
| 39 |
system_instruction=SYSTEM_INSTRUCTION
|
| 40 |
)
|
|
|
|
| 41 |
except Exception as e:
|
| 42 |
-
print(f"Error configuring Google Generative AI: {e}")
|
| 43 |
-
print("Please
|
| 44 |
model = None
|
| 45 |
|
| 46 |
-
#
|
| 47 |
app = Flask(__name__)
|
| 48 |
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
# --- Helper Functions
|
| 51 |
-
|
| 52 |
def get_available_diseases():
|
| 53 |
"""Scans the directory for available disease fact sheets."""
|
| 54 |
if not os.path.isdir(FACT_SHEET_DIR):
|
| 55 |
return []
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
def get_disease_fact_sheet(disease_name: str):
|
| 60 |
"""
|
| 61 |
-
|
| 62 |
-
It reads the content of a specific disease's text file from the local directory.
|
| 63 |
"""
|
| 64 |
-
print(f"
|
| 65 |
-
|
|
|
|
| 66 |
filename = disease_name.replace(' ', '_') + ".txt"
|
| 67 |
filepath = os.path.join(FACT_SHEET_DIR, filename)
|
| 68 |
|
| 69 |
if os.path.exists(filepath):
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
| 75 |
else:
|
| 76 |
-
print(f"
|
| 77 |
-
return {"error": f"Fact sheet not found for
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
# --- Main API Endpoint ---
|
| 81 |
|
|
|
|
| 82 |
@app.route('/ask', methods=['POST'])
|
| 83 |
def ask_question():
|
| 84 |
"""
|
| 85 |
-
|
| 86 |
-
|
| 87 |
"""
|
| 88 |
if not model:
|
| 89 |
-
return jsonify({
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
available_diseases = get_available_diseases()
|
|
|
|
| 103 |
if not available_diseases:
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
-
#
|
| 107 |
try:
|
| 108 |
-
#
|
| 109 |
-
# function and using its output to generate a final answer, thanks to
|
| 110 |
-
# automatic function calling and the system instruction.
|
| 111 |
chat = model.start_chat(enable_automatic_function_calling=True)
|
| 112 |
|
| 113 |
-
#
|
| 114 |
prompt = f"""
|
| 115 |
-
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
|
|
|
|
|
|
| 119 |
"""
|
| 120 |
|
| 121 |
-
print("
|
| 122 |
-
|
|
|
|
| 123 |
response = chat.send_message(
|
| 124 |
prompt,
|
| 125 |
-
tools=[get_disease_fact_sheet]
|
| 126 |
)
|
| 127 |
|
| 128 |
final_answer = response.text
|
| 129 |
-
print(f"
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
except Exception as e:
|
| 133 |
-
print(f"
|
| 134 |
-
return jsonify({
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
-
# --- To run the app ---
|
| 138 |
if __name__ == '__main__':
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
else:
|
| 144 |
-
print("
|
| 145 |
-
print(f"
|
| 146 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
# disease.py - FIXED VERSION
|
| 2 |
+
|
| 3 |
import os
|
| 4 |
import json
|
| 5 |
from flask import Flask, request, jsonify
|
|
|
|
| 11 |
# --- Configuration ---
|
| 12 |
FACT_SHEET_DIR = "Text_Files"
|
| 13 |
|
| 14 |
+
# --- System Instruction ---
|
|
|
|
|
|
|
| 15 |
SYSTEM_INSTRUCTION = """
|
| 16 |
You are a helpful Health Fact Sheet Assistant. Your role is to answer questions
|
| 17 |
about specific diseases based ONLY on the information contained in the fact sheets
|
|
|
|
| 27 |
6. Keep responses clear, short, and simple. Don't mention the source of the information.
|
| 28 |
"""
|
| 29 |
|
| 30 |
+
# Configure Gemini
|
| 31 |
try:
|
| 32 |
+
api_key = os.getenv("GOOGLE_API_KEY")
|
| 33 |
+
if not api_key:
|
| 34 |
+
raise ValueError("GOOGLE_API_KEY not found in environment")
|
| 35 |
+
|
| 36 |
+
genai.configure(api_key=api_key)
|
| 37 |
model = genai.GenerativeModel(
|
| 38 |
+
'gemini-2.0-flash-exp',
|
| 39 |
system_instruction=SYSTEM_INSTRUCTION
|
| 40 |
)
|
| 41 |
+
print("β
Gemini AI configured successfully")
|
| 42 |
except Exception as e:
|
| 43 |
+
print(f"β Error configuring Google Generative AI: {e}")
|
| 44 |
+
print("Please ensure GOOGLE_API_KEY is set in your .env file")
|
| 45 |
model = None
|
| 46 |
|
| 47 |
+
# Flask App
|
| 48 |
app = Flask(__name__)
|
| 49 |
|
| 50 |
+
# Create fact sheet directory if it doesn't exist
|
| 51 |
+
os.makedirs(FACT_SHEET_DIR, exist_ok=True)
|
| 52 |
|
| 53 |
+
# --- Helper Functions ---
|
|
|
|
| 54 |
def get_available_diseases():
|
| 55 |
"""Scans the directory for available disease fact sheets."""
|
| 56 |
if not os.path.isdir(FACT_SHEET_DIR):
|
| 57 |
return []
|
| 58 |
+
return [
|
| 59 |
+
os.path.splitext(f)[0].replace('_', ' ')
|
| 60 |
+
for f in os.listdir(FACT_SHEET_DIR)
|
| 61 |
+
if f.endswith(".txt")
|
| 62 |
+
]
|
| 63 |
|
| 64 |
def get_disease_fact_sheet(disease_name: str):
|
| 65 |
"""
|
| 66 |
+
Reads the content of a specific disease's text file.
|
|
|
|
| 67 |
"""
|
| 68 |
+
print(f"π Looking for fact sheet: '{disease_name}'")
|
| 69 |
+
|
| 70 |
+
# Convert to filename format
|
| 71 |
filename = disease_name.replace(' ', '_') + ".txt"
|
| 72 |
filepath = os.path.join(FACT_SHEET_DIR, filename)
|
| 73 |
|
| 74 |
if os.path.exists(filepath):
|
| 75 |
+
try:
|
| 76 |
+
with open(filepath, 'r', encoding='utf-8') as f:
|
| 77 |
+
content = f.read()
|
| 78 |
+
print(f"β
Found and read '{filename}'")
|
| 79 |
+
return {"disease": disease_name, "content": content}
|
| 80 |
+
except Exception as e:
|
| 81 |
+
print(f"β Error reading file: {e}")
|
| 82 |
+
return {"error": f"Could not read fact sheet for {disease_name}"}
|
| 83 |
else:
|
| 84 |
+
print(f"β οΈ Fact sheet not found for '{disease_name}'")
|
| 85 |
+
return {"error": f"Fact sheet not found for: {disease_name}"}
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
+
# --- API Endpoints ---
|
| 88 |
@app.route('/ask', methods=['POST'])
|
| 89 |
def ask_question():
|
| 90 |
"""
|
| 91 |
+
Handle disease-related queries.
|
| 92 |
+
Expects JSON with 'query' field.
|
| 93 |
"""
|
| 94 |
if not model:
|
| 95 |
+
return jsonify({
|
| 96 |
+
"error": "Gemini AI not configured. Check your API key.",
|
| 97 |
+
"status": "error"
|
| 98 |
+
}), 500
|
| 99 |
+
|
| 100 |
+
# Handle both JSON and form data
|
| 101 |
+
if request.is_json:
|
| 102 |
+
data = request.get_json()
|
| 103 |
+
user_query = data.get('query')
|
| 104 |
+
else:
|
| 105 |
+
user_query = request.form.get('query')
|
| 106 |
+
|
| 107 |
+
if not user_query:
|
| 108 |
+
return jsonify({
|
| 109 |
+
"error": "Missing 'query' in request",
|
| 110 |
+
"status": "error"
|
| 111 |
+
}), 400
|
| 112 |
+
|
| 113 |
+
print(f"\n{'='*60}")
|
| 114 |
+
print(f"π New query: '{user_query}'")
|
| 115 |
+
print(f"{'='*60}")
|
| 116 |
|
| 117 |
available_diseases = get_available_diseases()
|
| 118 |
+
|
| 119 |
if not available_diseases:
|
| 120 |
+
print("β οΈ No fact sheets available, using general knowledge")
|
| 121 |
+
# Continue with general knowledge if no fact sheets
|
| 122 |
+
available_diseases_str = "No specific disease fact sheets available"
|
| 123 |
+
else:
|
| 124 |
+
available_diseases_str = ', '.join(available_diseases)
|
| 125 |
+
print(f"π Available fact sheets: {len(available_diseases)} files")
|
| 126 |
|
| 127 |
+
# Generate response
|
| 128 |
try:
|
| 129 |
+
# Start chat with automatic function calling
|
|
|
|
|
|
|
| 130 |
chat = model.start_chat(enable_automatic_function_calling=True)
|
| 131 |
|
| 132 |
+
# Create prompt
|
| 133 |
prompt = f"""
|
| 134 |
+
User question: '{user_query}'
|
| 135 |
|
| 136 |
+
Available disease fact sheets: {available_diseases_str}
|
| 137 |
+
|
| 138 |
+
Please provide a helpful response. If a specific disease is mentioned and
|
| 139 |
+
we have a fact sheet for it, use the get_disease_fact_sheet tool to retrieve it.
|
| 140 |
"""
|
| 141 |
|
| 142 |
+
print("π€ Sending to Gemini AI...")
|
| 143 |
+
|
| 144 |
+
# Send message with tool
|
| 145 |
response = chat.send_message(
|
| 146 |
prompt,
|
| 147 |
+
tools=[get_disease_fact_sheet]
|
| 148 |
)
|
| 149 |
|
| 150 |
final_answer = response.text
|
| 151 |
+
print(f"β
Response generated")
|
| 152 |
+
|
| 153 |
+
return jsonify({
|
| 154 |
+
"status": "success",
|
| 155 |
+
"response": final_answer,
|
| 156 |
+
"available_diseases": len(available_diseases)
|
| 157 |
+
})
|
| 158 |
|
| 159 |
except Exception as e:
|
| 160 |
+
print(f"β Error: {e}")
|
| 161 |
+
return jsonify({
|
| 162 |
+
"error": f"Failed to generate response: {str(e)}",
|
| 163 |
+
"status": "error"
|
| 164 |
+
}), 500
|
| 165 |
+
|
| 166 |
+
@app.route('/health', methods=['GET'])
|
| 167 |
+
def health_check():
|
| 168 |
+
"""Health check endpoint"""
|
| 169 |
+
diseases = get_available_diseases()
|
| 170 |
+
return jsonify({
|
| 171 |
+
"status": "running",
|
| 172 |
+
"service": "disease_query",
|
| 173 |
+
"gemini_configured": model is not None,
|
| 174 |
+
"fact_sheets_available": len(diseases),
|
| 175 |
+
"available_diseases": diseases[:5] if diseases else [],
|
| 176 |
+
"port": 5001
|
| 177 |
+
})
|
| 178 |
+
|
| 179 |
+
@app.route('/', methods=['GET'])
|
| 180 |
+
def index():
|
| 181 |
+
"""Basic info endpoint"""
|
| 182 |
+
diseases = get_available_diseases()
|
| 183 |
+
return jsonify({
|
| 184 |
+
"service": "Disease Information API",
|
| 185 |
+
"endpoint": "/ask",
|
| 186 |
+
"methods": ["POST"],
|
| 187 |
+
"accepts": "JSON with 'query' field",
|
| 188 |
+
"fact_sheets": f"{len(diseases)} disease fact sheets available",
|
| 189 |
+
"example_request": {
|
| 190 |
+
"query": "What are the symptoms of diabetes?"
|
| 191 |
+
}
|
| 192 |
+
})
|
| 193 |
+
|
| 194 |
+
@app.route('/diseases', methods=['GET'])
|
| 195 |
+
def list_diseases():
|
| 196 |
+
"""List all available diseases"""
|
| 197 |
+
diseases = get_available_diseases()
|
| 198 |
+
return jsonify({
|
| 199 |
+
"available_diseases": diseases,
|
| 200 |
+
"count": len(diseases)
|
| 201 |
+
})
|
| 202 |
+
|
| 203 |
+
# --- File Upload Endpoint (optional) ---
|
| 204 |
+
@app.route('/upload_fact_sheet', methods=['POST'])
|
| 205 |
+
def upload_fact_sheet():
|
| 206 |
+
"""Upload a new disease fact sheet"""
|
| 207 |
+
if 'file' not in request.files:
|
| 208 |
+
return jsonify({"error": "No file provided"}), 400
|
| 209 |
+
|
| 210 |
+
file = request.files['file']
|
| 211 |
+
if file.filename == '' or not file.filename.endswith('.txt'):
|
| 212 |
+
return jsonify({"error": "Invalid file. Must be a .txt file"}), 400
|
| 213 |
+
|
| 214 |
+
try:
|
| 215 |
+
# Save the file
|
| 216 |
+
filename = file.filename.replace(' ', '_')
|
| 217 |
+
filepath = os.path.join(FACT_SHEET_DIR, filename)
|
| 218 |
+
file.save(filepath)
|
| 219 |
+
|
| 220 |
+
return jsonify({
|
| 221 |
+
"status": "success",
|
| 222 |
+
"message": f"Fact sheet '{filename}' uploaded successfully",
|
| 223 |
+
"total_fact_sheets": len(get_available_diseases())
|
| 224 |
+
})
|
| 225 |
+
except Exception as e:
|
| 226 |
+
return jsonify({"error": f"Failed to upload: {str(e)}"}), 500
|
| 227 |
|
|
|
|
| 228 |
if __name__ == '__main__':
|
| 229 |
+
print("="*60)
|
| 230 |
+
print("Starting Disease Query Service")
|
| 231 |
+
print(f"Fact sheets directory: {FACT_SHEET_DIR}")
|
| 232 |
+
|
| 233 |
+
# Check and list available fact sheets
|
| 234 |
+
diseases = get_available_diseases()
|
| 235 |
+
if diseases:
|
| 236 |
+
print(f"β
Loaded {len(diseases)} fact sheets:")
|
| 237 |
+
for disease in diseases[:5]:
|
| 238 |
+
print(f" - {disease}")
|
| 239 |
+
if len(diseases) > 5:
|
| 240 |
+
print(f" ... and {len(diseases) - 5} more")
|
| 241 |
else:
|
| 242 |
+
print("β οΈ No fact sheets found. Service will use general knowledge only.")
|
| 243 |
+
print(f"π‘ Add .txt files to '{FACT_SHEET_DIR}/' directory for specific disease info")
|
| 244 |
+
|
| 245 |
+
print("="*60)
|
| 246 |
+
app.run(debug=True, port=5001)
|