Muhammadtaha12 commited on
Commit
7c5e42b
·
verified ·
1 Parent(s): 6e433aa

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +269 -0
app.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from transformers import pipeline
3
+ import requests
4
+ from transformers import pipeline
5
+ import requests
6
+ from transformers import pipeline
7
+ from pymongo import MongoClient
8
+ import datetime
9
+ from flask import Flask, request, jsonify
10
+
11
+ # Initialize Flask app
12
+ app = Flask(__name__)
13
+
14
+ # Set up Hugging Face model for conversational AI
15
+ nlp = pipeline("conversational", model="microsoft/DialoGPT-medium")
16
+
17
+ # Set up MongoDB client for storing conversation history
18
+ client = MongoClient("mongodb://localhost:27017/") # Use your MongoDB URI if cloud-based
19
+ db = client.healthbot
20
+
21
+ # Function to fetch medical information using an API
22
+ def get_medical_info(query):
23
+ # Example API call (replace with real API or local dataset)
24
+ api_url = f'https://api.healthapi.com/v1/query/{query}'
25
+ headers = {'Authorization': 'Bearer YOUR_API_KEY'} # Replace with your API key
26
+
27
+ try:
28
+ response = requests.get(api_url, headers=headers)
29
+ if response.status_code == 200:
30
+ return response.json() # Example: {'description': 'Details about the symptom'}
31
+ else:
32
+ return {'error': 'Could not retrieve information from API.'}
33
+ except Exception as e:
34
+ return {'error': str(e)}
35
+
36
+ # Save conversations to MongoDB
37
+ def save_conversation(user_input, bot_response):
38
+ conversation = {
39
+ 'timestamp': datetime.datetime.now(),
40
+ 'user_input': user_input,
41
+ 'bot_response': bot_response
42
+ }
43
+ db.conversations.insert_one(conversation)
44
+
45
+ # Get the last 5 conversations from memory
46
+ def get_previous_conversations():
47
+ return db.conversations.find().sort("timestamp", -1).limit(5)
48
+
49
+ # Main function to handle user input
50
+ def handle_user_input(user_input):
51
+ # If the input contains the word 'symptom', fetch medical info
52
+ if 'symptom' in user_input.lower():
53
+ query = user_input.lower().replace('symptom', '')
54
+ medical_info = get_medical_info(query)
55
+ if 'error' in medical_info:
56
+ return f"Sorry, we couldn't find information about '{query}'. Please try again."
57
+ else:
58
+ return f"Based on your query '{query}', here is some information: {medical_info.get('description', 'No details found.')}"
59
+ else:
60
+ # Otherwise, handle general conversation
61
+ response = nlp(user_input)
62
+ return response[0]['generated_text']
63
+
64
+ # Flask route to handle chatbot interaction
65
+ @app.route('/chat', methods=['POST'])
66
+ def chat():
67
+ user_input = request.json.get('user_input')
68
+ if not user_input:
69
+ return jsonify({'error': 'User input is required'}), 400
70
+
71
+ # Get response from chatbot
72
+ bot_response = handle_user_input(user_input)
73
+
74
+ # Save the conversation to memory
75
+ save_conversation(user_input, bot_response)
76
+
77
+ return jsonify({'response': bot_response})
78
+
79
+ # Flask route to retrieve previous conversations
80
+ @app.route('/history', methods=['GET'])
81
+ def history():
82
+ conversations = get_previous_conversations()
83
+ history = []
84
+ for convo in conversations:
85
+ history.append({
86
+ 'timestamp': convo['timestamp'].strftime('%Y-%m-%d %H:%M:%S'),
87
+ 'user_input': convo['user_input'],
88
+ 'bot_response': convo['bot_response']
89
+ })
90
+ return jsonify(history)
91
+
92
+ # Run the Flask app
93
+ if __name__ == "__main__":
94
+ app.run(debug=True)
95
+
96
+ import datetime
97
+ from flask import Flask, request, jsonify
98
+
99
+ # Initialize Flask app
100
+ app = Flask(__name__)
101
+
102
+ # Set up Hugging Face model for conversational AI
103
+ nlp = pipeline("conversational", model="microsoft/DialoGPT-medium")
104
+
105
+ # Set up MongoDB client for storing conversation history
106
+ client = MongoClient("mongodb://localhost:27017/") # Use your MongoDB URI if cloud-based
107
+ db = client.healthbot
108
+
109
+ # Function to fetch medical information using an API
110
+ def get_medical_info(query):
111
+ # Example API call (replace with real API or local dataset)
112
+ api_url = f'https://api.healthapi.com/v1/query/{query}'
113
+ headers = {'Authorization': 'Bearer YOUR_API_KEY'} # Replace with your API key
114
+
115
+ try:
116
+ response = requests.get(api_url, headers=headers)
117
+ if response.status_code == 200:
118
+ return response.json() # Example: {'description': 'Details about the symptom'}
119
+ else:
120
+ return {'error': 'Could not retrieve information from API.'}
121
+ except Exception as e:
122
+ return {'error': str(e)}
123
+
124
+ # Save conversations to MongoDB
125
+ def save_conversation(user_input, bot_response):
126
+ conversation = {
127
+ 'timestamp': datetime.datetime.now(),
128
+ 'user_input': user_input,
129
+ 'bot_response': bot_response
130
+ }
131
+ db.conversations.insert_one(conversation)
132
+
133
+ # Get the last 5 conversations from memory
134
+ def get_previous_conversations():
135
+ return db.conversations.find().sort("timestamp", -1).limit(5)
136
+
137
+ # Main function to handle user input
138
+ def handle_user_input(user_input):
139
+ # If the input contains the word 'symptom', fetch medical info
140
+ if 'symptom' in user_input.lower():
141
+ query = user_input.lower().replace('symptom', '')
142
+ medical_info = get_medical_info(query)
143
+ if 'error' in medical_info:
144
+ return f"Sorry, we couldn't find information about '{query}'. Please try again."
145
+ else:
146
+ return f"Based on your query '{query}', here is some information: {medical_info.get('description', 'No details found.')}"
147
+ else:
148
+ # Otherwise, handle general conversation
149
+ response = nlp(user_input)
150
+ return response[0]['generated_text']
151
+
152
+ # Flask route to handle chatbot interaction
153
+ @app.route('/chat', methods=['POST'])
154
+ def chat():
155
+ user_input = request.json.get('user_input')
156
+ if not user_input:
157
+ return jsonify({'error': 'User input is required'}), 400
158
+
159
+ # Get response from chatbot
160
+ bot_response = handle_user_input(user_input)
161
+
162
+ # Save the conversation to memory
163
+ save_conversation(user_input, bot_response)
164
+
165
+ return jsonify({'response': bot_response})
166
+
167
+ # Flask route to retrieve previous conversations
168
+ @app.route('/history', methods=['GET'])
169
+ def history():
170
+ conversations = get_previous_conversations()
171
+ history = []
172
+ for convo in conversations:
173
+ history.append({
174
+ 'timestamp': convo['timestamp'].strftime('%Y-%m-%d %H:%M:%S'),
175
+ 'user_input': convo['user_input'],
176
+ 'bot_response': convo['bot_response']
177
+ })
178
+ return jsonify(history)
179
+
180
+ # Run the Flask app
181
+ if __name__ == "__main__":
182
+ app.run(debug=True)
183
+ import datetime
184
+ from flask import Flask, request, jsonify
185
+
186
+ # Initialize Flask app
187
+ app = Flask(__name__)
188
+
189
+ # Set up Hugging Face model for conversational AI
190
+ nlp = pipeline("conversational", model="microsoft/DialoGPT-medium")
191
+
192
+ # Set up MongoDB client for storing conversation history
193
+ client = MongoClient("mongodb://localhost:27017/") # Use your MongoDB URI if cloud-based
194
+ db = client.healthbot
195
+
196
+ # Function to fetch medical information using an API
197
+ def get_medical_info(query):
198
+ # Example API call (replace with real API or local dataset)
199
+ api_url = f'https://api.healthapi.com/v1/query/{query}'
200
+ headers = {'Authorization': 'Bearer YOUR_API_KEY'} # Replace with your API key
201
+
202
+ try:
203
+ response = requests.get(api_url, headers=headers)
204
+ if response.status_code == 200:
205
+ return response.json() # Example: {'description': 'Details about the symptom'}
206
+ else:
207
+ return {'error': 'Could not retrieve information from API.'}
208
+ except Exception as e:
209
+ return {'error': str(e)}
210
+
211
+ # Save conversations to MongoDB
212
+ def save_conversation(user_input, bot_response):
213
+ conversation = {
214
+ 'timestamp': datetime.datetime.now(),
215
+ 'user_input': user_input,
216
+ 'bot_response': bot_response
217
+ }
218
+ db.conversations.insert_one(conversation)
219
+
220
+ # Get the last 5 conversations from memory
221
+ def get_previous_conversations():
222
+ return db.conversations.find().sort("timestamp", -1).limit(5)
223
+
224
+ # Main function to handle user input
225
+ def handle_user_input(user_input):
226
+ # If the input contains the word 'symptom', fetch medical info
227
+ if 'symptom' in user_input.lower():
228
+ query = user_input.lower().replace('symptom', '')
229
+ medical_info = get_medical_info(query)
230
+ if 'error' in medical_info:
231
+ return f"Sorry, we couldn't find information about '{query}'. Please try again."
232
+ else:
233
+ return f"Based on your query '{query}', here is some information: {medical_info.get('description', 'No details found.')}"
234
+ else:
235
+ # Otherwise, handle general conversation
236
+ response = nlp(user_input)
237
+ return response[0]['generated_text']
238
+
239
+ # Flask route to handle chatbot interaction
240
+ @app.route('/chat', methods=['POST'])
241
+ def chat():
242
+ user_input = request.json.get('user_input')
243
+ if not user_input:
244
+ return jsonify({'error': 'User input is required'}), 400
245
+
246
+ # Get response from chatbot
247
+ bot_response = handle_user_input(user_input)
248
+
249
+ # Save the conversation to memory
250
+ save_conversation(user_input, bot_response)
251
+
252
+ return jsonify({'response': bot_response})
253
+
254
+ # Flask route to retrieve previous conversations
255
+ @app.route('/history', methods=['GET'])
256
+ def history():
257
+ conversations = get_previous_conversations()
258
+ history = []
259
+ for convo in conversations:
260
+ history.append({
261
+ 'timestamp': convo['timestamp'].strftime('%Y-%m-%d %H:%M:%S'),
262
+ 'user_input': convo['user_input'],
263
+ 'bot_response': convo['bot_response']
264
+ })
265
+ return jsonify(history)
266
+
267
+ # Run the Flask app
268
+ if __name__ == "__main__":
269
+ app.run(debug=True)