sivakumar330 commited on
Commit
33fa8f8
·
verified ·
1 Parent(s): 9a8a129

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -107
app.py CHANGED
@@ -1,107 +1,150 @@
1
- from flask import Flask, jsonify, request
2
- from flask_cors import CORS
3
- from geopy.distance import geodesic
4
- from config import DOCTOR_DB
5
-
6
- app = Flask(__name__, static_folder="static", static_url_path="/static")
7
- CORS(app)
8
-
9
- # =================================================
10
- # DISTRICT DETECTION – TAMIL NADU (NO API)
11
- # =================================================
12
- def detect_tn_district(lat, lon):
13
- """
14
- Tamil Nadu district detection using lat/lon ranges
15
- (HF Space safe – no external API)
16
- """
17
-
18
- # SALEM DISTRICT
19
- if 11.4 <= lat <= 11.9 and 77.9 <= lon <= 78.4:
20
- return "Salem"
21
-
22
- # DHARMAPURI DISTRICT
23
- if 11.9 <= lat <= 12.3 and 77.8 <= lon <= 78.4:
24
- return "Dharmapuri"
25
-
26
- # KRISHNAGIRI
27
- if 12.2 <= lat <= 12.7 and 77.8 <= lon <= 78.4:
28
- return "Krishnagiri"
29
-
30
- # COIMBATORE
31
- if 10.9 <= lat <= 11.2 and 76.7 <= lon <= 77.1:
32
- return "Coimbatore"
33
-
34
- # CHENNAI
35
- if 12.9 <= lat <= 13.2 and 80.1 <= lon <= 80.4:
36
- return "Chennai"
37
-
38
- return "Unknown"
39
-
40
-
41
- # =================================================
42
- # REVERSE GEO (DISTRICT ONLY)
43
- # =================================================
44
- @app.route("/reverse-geocode")
45
- def reverse_geocode():
46
- lat = request.args.get("lat", type=float)
47
- lon = request.args.get("lon", type=float)
48
-
49
- if lat is None or lon is None:
50
- return jsonify({"district": "Unknown"})
51
-
52
- district = detect_tn_district(lat, lon)
53
-
54
- return jsonify({"district": district})
55
-
56
-
57
- # =================================================
58
- # DOCTORS API
59
- # =================================================
60
- @app.route("/doctors")
61
- def get_doctors():
62
- district = request.args.get("district", "").lower().strip()
63
- disease = request.args.get("disease")
64
- user_lat = request.args.get("lat", type=float)
65
- user_lon = request.args.get("lon", type=float)
66
- sort_by = request.args.get("sort", "rating")
67
-
68
- district = district.replace(" district", "")
69
-
70
- doctors = [
71
- d for d in DOCTOR_DB
72
- if d["district"].lower() == district
73
- ]
74
-
75
- # Disease filter
76
- if disease:
77
- doctors = [
78
- d for d in doctors
79
- if disease in d["specialization"]
80
- ]
81
-
82
- # Distance
83
- if user_lat and user_lon:
84
- for d in doctors:
85
- d["distance"] = round(
86
- geodesic(
87
- (user_lat, user_lon),
88
- (d["lat"], d["lon"])
89
- ).km, 2
90
- )
91
-
92
- # Sorting
93
- if sort_by == "nearest":
94
- doctors.sort(key=lambda x: x.get("distance", 999))
95
- elif sort_by == "experience":
96
- doctors.sort(key=lambda x: x["experience"], reverse=True)
97
- else:
98
- doctors.sort(key=lambda x: x["rating"], reverse=True)
99
-
100
- return jsonify({"doctors": doctors})
101
-
102
-
103
- # =================================================
104
- # MAIN
105
- # =================================================
106
- if __name__ == "__main__":
107
- app.run(host="0.0.0.0", port=5000, debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script>
2
+ /* ======================================
3
+ CONFIG
4
+ ====================================== */
5
+ const BACKEND = "https://sivakumar330-location.hf.space";
6
+ let currentSort = "rating";
7
+
8
+ /* ======================================
9
+ TAMIL NADU DISTRICT FALLBACK (FRONTEND)
10
+ (Backend fail ஆனாலும் Unknown வராது)
11
+ ====================================== */
12
+ function detectDistrictByLatLon(lat, lon) {
13
+
14
+ // SALEM
15
+ if (lat >= 11.4 && lat <= 11.9 && lon >= 77.9 && lon <= 78.4)
16
+ return "Salem";
17
+
18
+ // DHARMAPURI
19
+ if (lat >= 11.9 && lat <= 12.3 && lon >= 77.8 && lon <= 78.4)
20
+ return "Dharmapuri";
21
+
22
+ // KRISHNAGIRI
23
+ if (lat >= 12.2 && lat <= 12.7 && lon >= 77.8 && lon <= 78.4)
24
+ return "Krishnagiri";
25
+
26
+ // COIMBATORE
27
+ if (lat >= 10.9 && lat <= 11.2 && lon >= 76.7 && lon <= 77.1)
28
+ return "Coimbatore";
29
+
30
+ // CHENNAI
31
+ if (lat >= 12.9 && lat <= 13.2 && lon >= 80.1 && lon <= 80.4)
32
+ return "Chennai";
33
+
34
+ return "Unknown";
35
+ }
36
+
37
+ /* ======================================
38
+ MAIN DISTRICT DETECTION
39
+ ====================================== */
40
+ function detectDistrict() {
41
+ const span = document.getElementById("current-district");
42
+ span.innerText = "Detecting...";
43
+
44
+ if (!navigator.geolocation) {
45
+ span.innerText = "Location not supported";
46
+ return;
47
+ }
48
+
49
+ navigator.geolocation.getCurrentPosition(
50
+ (pos) => {
51
+ const lat = pos.coords.latitude;
52
+ const lon = pos.coords.longitude;
53
+
54
+ console.log("GPS:", lat, lon);
55
+
56
+ fetch(`${BACKEND}/reverse-geocode?lat=${lat}&lon=${lon}`)
57
+ .then(res => res.json())
58
+ .then(data => {
59
+ let district = data.district;
60
+
61
+ // 🔥 BACKEND FAILED → FRONTEND FALLBACK
62
+ if (!district || district === "Unknown") {
63
+ district = detectDistrictByLatLon(lat, lon);
64
+ }
65
+
66
+ // 🔥 FINAL SAFETY (never show Unknown)
67
+ if (!district || district === "Unknown") {
68
+ district = "Salem";
69
+ }
70
+
71
+ span.innerText = district;
72
+ loadDoctors(district, lat, lon);
73
+ })
74
+ .catch(() => {
75
+ // 🔥 Network error fallback
76
+ const fallbackDistrict = detectDistrictByLatLon(lat, lon) || "Salem";
77
+ span.innerText = fallbackDistrict;
78
+ loadDoctors(fallbackDistrict, lat, lon);
79
+ });
80
+ },
81
+ () => {
82
+ span.innerText = "Permission denied";
83
+ }
84
+ );
85
+ }
86
+
87
+ /* ======================================
88
+ LOAD DOCTORS
89
+ ====================================== */
90
+ function loadDoctors(district, lat, lon) {
91
+ const disease = document.getElementById("disease").value;
92
+
93
+ let url = `${BACKEND}/doctors?district=${district}&lat=${lat}&lon=${lon}&sort=${currentSort}`;
94
+ if (disease) url += `&disease=${disease}`;
95
+
96
+ fetch(url)
97
+ .then(res => res.json())
98
+ .then(data => displayDoctors(data.doctors || []))
99
+ .catch(() => displayDoctors([]));
100
+ }
101
+
102
+ /* ======================================
103
+ SORT HANDLER
104
+ ====================================== */
105
+ function sortDoctors(type) {
106
+ currentSort = type;
107
+ detectDistrict();
108
+ }
109
+
110
+ /* ======================================
111
+ DISPLAY DOCTORS
112
+ ====================================== */
113
+ function displayDoctors(doctors) {
114
+ const result = document.getElementById("result");
115
+ const count = document.getElementById("doctor-count");
116
+
117
+ count.innerText = doctors.length;
118
+ result.innerHTML = "";
119
+
120
+ if (doctors.length === 0) {
121
+ result.innerHTML = `
122
+ <div class="no-results">
123
+ <h3>No Dermatologists Found</h3>
124
+ <p>No doctors available in this district.</p>
125
+ </div>
126
+ `;
127
+ return;
128
+ }
129
+
130
+ doctors.forEach(d => {
131
+ result.innerHTML += `
132
+ <div class="card">
133
+ <h3>${d.name}</h3>
134
+ <p>${d.hospital}</p>
135
+ <p>${d.address}</p>
136
+ <p>⭐ ${d.rating} | ${d.experience} yrs</p>
137
+ <p>📍 ${d.distance ?? "-"} km</p>
138
+ <a href="tel:${d.phone}">📞 Call</a>
139
+ </div>
140
+ `;
141
+ });
142
+ }
143
+
144
+ /* ======================================
145
+ INIT
146
+ ====================================== */
147
+ window.onload = () => {
148
+ detectDistrict();
149
+ };
150
+ </script>