From c70bcf08d81a65c7ea26bdda7f4a2792f85f8f7d Mon Sep 17 00:00:00 2001 From: Pritimay Sarkar Date: Sun, 10 Dec 2023 13:56:56 +0530 Subject: [PATCH] add cloud function my_function --- cloud-functions/python/functions/main.py | 131 ++++++++---------- .../python/functions/requirements.txt | 3 +- 2 files changed, 60 insertions(+), 74 deletions(-) diff --git a/cloud-functions/python/functions/main.py b/cloud-functions/python/functions/main.py index d86b3eb..6962b2c 100644 --- a/cloud-functions/python/functions/main.py +++ b/cloud-functions/python/functions/main.py @@ -1,83 +1,68 @@ -# Deploy with `firebase deploy` - -from firebase_functions import https_fn -from firebase_admin import initialize_app, firestore -import pandas as pd -import datetime -import sys -import platform +import functions_framework +# from google.cloud.firestore_v1.base_query import FieldFilter +# from firebase_admin import initialize_app, credentials, firestore import os +from datetime import datetime +import pickle +# import pandas as pd -# initialize_app() -# -# -# @https_fn.on_request() -# def on_request_example(req: https_fn.Request) -> https_fn.Response: -# return https_fn.Response("Hello world!") +@functions_framework.http +def my_function(request): + """HTTP Cloud Function. + Args: + request (flask.Request): The request object. + + Returns: + The response text, or any set of values that can be turned into a + Response object using `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( -# cors=options.CorsOptions( -# cors_origins=[r"firebase\.com$", r"https://flutter\.com"], -# cors_methods=["get", "post"], -# ) -# ) + headers = { + 'Access-Control-Allow-Origin': '*' + } -initialize_app() + with open('label_encoder.pkl', 'rb') as label_encoder_file: + loaded_label_encoder = pickle.load(label_encoder_file) -@https_fn.on_request() -def consolidation(req: https_fn.Request) -> https_fn.Response: + with open('gaussian_naive_bayes_model.pkl', 'rb') as model_file: + loaded_model = pickle.load(model_file) - path_delim = "/" - - db = firestore.client() - - patient_collection = db.collection("patientData") - test_collection = db.collection("testData") - - start_date = req.query.start_date - print("start_date", start_date) - end_date = req.query.end_date - print("end_date", end_date) - - - query = test_collection # test_collection.where(filter=FieldFilter("testTime", ">=", start_date)).where(filter=FieldFilter("testTime", "<", end_date)) - patient_docs = query.stream() - - data = [] - 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()) + input_data = pd.DataFrame({'calculatedRatio': 0.231057205, 'deviceRatio': 0.231057205,'led1Buffer': 23776.33, 'led2Buffer': 26401.67, + 'led1Sample': 16286, 'led2Sample': 6952.67}, index=[0]) + predicted_result = loaded_model.predict(input_data) + print(predicted_result.item()) - # return https_fn.Response(response = send_file(output_path)) +# db = firestore.client() +# source_collection = "testData" - return https_fn.Response("Ok!") + # # Get all documents from the source collection + # source_docs = db.collection(source_collection).where(filter=FieldFilter("createdAt", ">=", datetime.today().strftime("%Y-%m-%d"))).stream() + # count = 0 + # 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() + + # try: + # # 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}") + + return ('prediction applied: {}!'.format(0), 200, headers) diff --git a/cloud-functions/python/functions/requirements.txt b/cloud-functions/python/functions/requirements.txt index b4ad0cc..df9b31b 100644 --- a/cloud-functions/python/functions/requirements.txt +++ b/cloud-functions/python/functions/requirements.txt @@ -2,4 +2,5 @@ functions-framework==3.* firebase_functions~=0.1.0 pandas==2.0.3 openpyxl==3.1.2 -firebase-admin==6.2.0 \ No newline at end of file +firebase-admin==6.2.0 +scikit-learn==1.3.1 \ No newline at end of file