-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblood_ai_extended.py
More file actions
106 lines (87 loc) · 3.01 KB
/
blood_ai_extended.py
File metadata and controls
106 lines (87 loc) · 3.01 KB
1
2
3
4
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
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
# blood_ai_extended.py
import google.generativeai as genai
import json
import pickle
import os
import requests
import re
# Load your trained model
with open("blood_model.pkl", "rb") as f:
model = pickle.load(f)
# 🔑 Set Gemini API key
genai.configure(api_key="your_api_key_here") # <-- Replace this with your actual key
# Gemini model setup
model_name = "models/gemini-1.5-pro"
chat = genai.GenerativeModel(model_name).start_chat()
# 🩸 User input
prompt = input("\n🩸 Enter patient's condition & blood request: ")
# Ask Gemini to extract structured info
response = chat.send_message(f"""
Extract the blood request in this exact JSON format:
{{
"urgency_level": "",
"blood_group": "",
"units_needed": 0,
"purity_required": "",
"city": ""
}}
Message: {prompt}
""")
# 🧠 Get Gemini reply as text
response_text = response.text.strip()
print("\n🔍 Gemini Raw Response:\n", response_text)
# ✅ Clean and extract JSON block only
match = re.search(r"\{.*\}", response_text, re.DOTALL)
if not match:
print("❌ Error: No valid JSON found in Gemini response.")
exit()
try:
info = json.loads(match.group())
except json.JSONDecodeError:
print("❌ Error: Failed to parse Gemini response into JSON.")
exit()
# 📋 Display info
print("\n🧾 Extracted Info:")
for key, val in info.items():
print(f"{key.capitalize().replace('_', ' ')}: {val}")
# Dummy feature values for model prediction
recency = 2
frequency = 3
monetary = info.get("units_needed", 1)
time = 4
# Model prediction
prediction = model.predict([[recency, frequency, monetary, time]])[0]
print("\n🤖 AI Prediction:")
if prediction == 1:
print("✅ Proceed: Blood request is likely valid and can be fulfilled.")
else:
print("⚠️ Caution: Blood request may not be prioritized, review further.")
# 📍 Find nearby hospitals
def find_hospitals(city):
print(f"\n🔍 Searching hospitals in: {city}")
url = f"https://nominatim.openstreetmap.org/search.php?q=hospital+in+{city}&format=jsonv2"
try:
res = requests.get(url)
hospitals = res.json()
if hospitals:
print("\n🏥 Nearby Hospitals:")
for i, h in enumerate(hospitals[:3], 1):
print(f"{i}. {h.get('display_name')}")
else:
print("No hospitals found.")
except Exception as e:
print("Error fetching hospital info:", e)
if info.get("city"):
find_hospitals(info["city"])
# 📨 Simulate notifications
print("\n📩 Notifying donors of blood type:", info.get("blood_group"))
print("📍 Sharing recipient hospital/location to matched donors.")
# 🛰️ Simulate tracking
donor_location = "Donor at 13.0827°N, 80.2707°E (Chennai)"
recipient_location = f"Recipient in {info.get('city', 'unknown')}"
print(f"\n📡 Tracking started:")
print(f" - Donor: {donor_location}")
print(f" - Recipient: {recipient_location}")
# 🔔 Notify blood bank
print("\n🔔 Blood bank notified about urgent request for", info.get("blood_group"))
print("📞 Blood bank is on the way to hospital.")