add cloud function my_function

This commit is contained in:
Pritimay Sarkar
2023-12-10 13:56:56 +05:30
parent ada269af48
commit c70bcf08d8
2 changed files with 60 additions and 74 deletions

View File

@@ -1,83 +1,68 @@
# Deploy with `firebase deploy` import functions_framework
# from google.cloud.firestore_v1.base_query import FieldFilter
from firebase_functions import https_fn # from firebase_admin import initialize_app, credentials, firestore
from firebase_admin import initialize_app, firestore
import pandas as pd
import datetime
import sys
import platform
import os import os
from datetime import datetime
import pickle
# import pandas as pd
# initialize_app() @functions_framework.http
# def my_function(request):
# """HTTP Cloud Function.
# @https_fn.on_request() Args:
# def on_request_example(req: https_fn.Request) -> https_fn.Response: request (flask.Request): The request object.
# return https_fn.Response("Hello world!") <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
Returns:
The response text, or any set of values that can be turned into a
Response object using `make_response`
<https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
"""
if request.method == 'OPTIONS':
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type',
# 'Access-Control-Max-Age': '3600'
}
return ('', 204, headers)
# @https_fn.on_request( headers = {
# cors=options.CorsOptions( 'Access-Control-Allow-Origin': '*'
# cors_origins=[r"firebase\.com$", r"https://flutter\.com"], }
# cors_methods=["get", "post"],
# )
# )
initialize_app() with open('label_encoder.pkl', 'rb') as label_encoder_file:
loaded_label_encoder = pickle.load(label_encoder_file)
@https_fn.on_request() with open('gaussian_naive_bayes_model.pkl', 'rb') as model_file:
def consolidation(req: https_fn.Request) -> https_fn.Response: loaded_model = pickle.load(model_file)
path_delim = "/" input_data = pd.DataFrame({'calculatedRatio': 0.231057205, 'deviceRatio': 0.231057205,'led1Buffer': 23776.33, 'led2Buffer': 26401.67,
'led1Sample': 16286, 'led2Sample': 6952.67}, index=[0])
db = firestore.client() predicted_result = loaded_model.predict(input_data)
print(predicted_result.item())
patient_collection = db.collection("patientData") # db = firestore.client()
test_collection = db.collection("testData") # source_collection = "testData"
start_date = req.query.start_date # # Get all documents from the source collection
print("start_date", start_date) # source_docs = db.collection(source_collection).where(filter=FieldFilter("createdAt", ">=", datetime.today().strftime("%Y-%m-%d"))).stream()
end_date = req.query.end_date # count = 0
print("end_date", end_date) # for doc in source_docs:
# # Extract the document ID
# doc_id = doc.id
# print(doc_id)
# # Get the document data
# doc_data = doc.to_dict()
query = test_collection # test_collection.where(filter=FieldFilter("testTime", ">=", start_date)).where(filter=FieldFilter("testTime", "<", end_date)) # try:
patient_docs = query.stream() # # Delete the document from the source collection
# db.collection(source_collection).document(doc_id).delete()
# print(f"Document with ID '{doc_id}' updated")
# count = count + 1
# except Exception as e:
# print(f"Error deleting document with ID '{doc_id}' from the source collection: {e}")
data = [] return ('prediction applied: {}!'.format(0), 200, headers)
for patient_doc in patient_docs:
patient_data = patient_doc.to_dict()
patient_id = patient_data["_id"]
test_docs = test_collection.where("_id", "==", patient_id).stream()
for test_doc in test_docs:
test_data = test_doc.to_dict()
combined_data = {**patient_data, **test_data}
for key, value in combined_data.items():
if value == "" and key in patient_data:
combined_data[key] = patient_data[key]
data.append(combined_data)
df = pd.DataFrame(data)
output_filename = "data.xlsx"
df.to_csv(output_filename, index=False)
output_path = os.getcwd() + path_delim + output_filename
writer = pd.ExcelWriter(output_path, engine = 'openpyxl')
df = df[(df['testTime'] > start_date) & (df['testTime'] <= end_date)]
df = df.sort_values(by=['testTime'], ascending=False)
df = df.drop(['resultData', "reportUploadTime", "userImageURL", "testType", "birthYear", "testStatus", "reportPath", "createdBy", "csvPath", "result", "mobileId", "resultRatio", "localFlag", "led2", "led1"], axis=1)
df.to_excel(writer, sheet_name = 'data', index=False)
writer.close()
firebase_admin.delete_app(firebase_admin.get_app())
# return https_fn.Response(response = send_file(output_path))
return https_fn.Response("Ok!")

View File

@@ -3,3 +3,4 @@ firebase_functions~=0.1.0
pandas==2.0.3 pandas==2.0.3
openpyxl==3.1.2 openpyxl==3.1.2
firebase-admin==6.2.0 firebase-admin==6.2.0
scikit-learn==1.3.1