NitinBot001 commited on
Commit
8c73350
Β·
verified Β·
1 Parent(s): 38ba0de

Update disease.py

Browse files
Files changed (1) hide show
  1. 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 for the Gemini Model ---
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 the Google Generative AI SDK.
31
  try:
32
- # This will automatically look for the GOOGLE_API_KEY environment variable.
33
- genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
34
-
35
- # Initialize the Gemini model with the system instruction.
36
- # We recommend using a model that is highly optimized for tool use.
37
  model = genai.GenerativeModel(
38
- 'gemini-1.5-flash',
39
  system_instruction=SYSTEM_INSTRUCTION
40
  )
 
41
  except Exception as e:
42
- print(f"Error configuring Google Generative AI: {e}")
43
- print("Please make sure your GOOGLE_API_KEY environment variable is set.")
44
  model = None
45
 
46
- # --- Flask App Initialization ---
47
  app = Flask(__name__)
48
 
 
 
49
 
50
- # --- Helper Functions (Tool Implementation) ---
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
- # Create a clean list of names from filenames (e.g., "Chickenpox_and_Shingles.txt" -> "Chickenpox and Shingles")
57
- return [os.path.splitext(f)[0].replace('_', ' ') for f in os.listdir(FACT_SHEET_DIR) if f.endswith(".txt")]
 
 
 
58
 
59
  def get_disease_fact_sheet(disease_name: str):
60
  """
61
- This is the actual Python function that gets executed by the model.
62
- It reads the content of a specific disease's text file from the local directory.
63
  """
64
- print(f"--- TOOL EXECUTION: Running get_disease_fact_sheet(disease_name='{disease_name}') ---")
65
- # Convert the friendly name back to a filename format
 
66
  filename = disease_name.replace(' ', '_') + ".txt"
67
  filepath = os.path.join(FACT_SHEET_DIR, filename)
68
 
69
  if os.path.exists(filepath):
70
- with open(filepath, 'r', encoding='utf-8') as f:
71
- content = f.read()
72
- print(f"--- SUCCESS: Found and read '{filename}' ---")
73
- # Return a dictionary, which will be implicitly handled by the Gemini SDK
74
- return {"disease": disease_name, "content": content}
 
 
 
75
  else:
76
- print(f"--- ERROR: Fact sheet not found for '{disease_name}' ---")
77
- return {"error": f"Fact sheet not found for the disease: {disease_name}."}
78
-
79
-
80
- # --- Main API Endpoint ---
81
 
 
82
  @app.route('/ask', methods=['POST'])
83
  def ask_question():
84
  """
85
- Handles user queries by orchestrating the interaction with the Gemini model,
86
- which is guided by the system instruction to use the provided tools and context.
87
  """
88
  if not model:
89
- return jsonify({"error": "Gemini client is not configured. Check your API key."}), 500
90
-
91
- data = request.get_json()
92
- form_data = request.form
93
- if not form_data and 'query' not in data:
94
- return jsonify({"error": "Request must be JSON and contain a 'query' field."}), 400
95
-
96
- user_query = data['query'] or form_data['query']
97
- print(f"\n=================================================")
98
- print(f"Received new query: '{user_query}'")
99
- print(f"=================================================")
100
-
 
 
 
 
 
 
 
 
 
101
 
102
  available_diseases = get_available_diseases()
 
103
  if not available_diseases:
104
- return jsonify({"error": f"No fact sheets found in the '{FACT_SHEET_DIR}' directory."}), 500
 
 
 
 
 
105
 
106
- # === Orchestration with Gemini ===
107
  try:
108
- # We start a chat session. The model will automatically handle calling the
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
- # Construct a more informative prompt for the model.
114
  prompt = f"""
115
- Here is the user's question: '{user_query}'
116
 
117
- Please use your tools to answer it. The available diseases you can look up are:
118
- {', '.join(available_diseases)}
 
 
119
  """
120
 
121
- print("--- Sending request to Gemini... ---")
122
- # Send the user's query and the definitions of the available tools
 
123
  response = chat.send_message(
124
  prompt,
125
- tools=[get_disease_fact_sheet] # Pass the actual function reference
126
  )
127
 
128
  final_answer = response.text
129
- print(f"--- Gemini's Final Answer: ---\n{final_answer}\n")
130
- return jsonify({"response": final_answer})
 
 
 
 
 
131
 
132
  except Exception as e:
133
- print(f"--- An unexpected error occurred: {e} ---")
134
- return jsonify({"error": f"Gemini API Error: {e}"}), 500
135
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
- # --- To run the app ---
138
  if __name__ == '__main__':
139
- # Make sure the Text_Files directory exists before starting
140
- if not os.path.isdir(FACT_SHEET_DIR):
141
- print(f"CRITICAL ERROR: The directory '{FACT_SHEET_DIR}' does not exist.")
142
- print("Please create it and populate it with the disease .txt files.")
 
 
 
 
 
 
 
 
143
  else:
144
- print("Starting Flask server...")
145
- print(f"Fact sheets loaded for: {', '.join(get_available_diseases())}")
146
- app.run(debug=True, port=5001)
 
 
 
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)