deepak6593 commited on
Commit
03dc0ec
·
1 Parent(s): 92f1b25
Files changed (1) hide show
  1. test.py +89 -0
test.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Query
2
+ import csv
3
+ import os
4
+ from threading import Thread
5
+ import time
6
+ import pandas as pd
7
+ import tempfile
8
+ from google.cloud import storage
9
+
10
+ app = FastAPI()
11
+
12
+ data_location = None
13
+ reading_thread = None
14
+ stop_reading = False
15
+ counter = 0
16
+
17
+ gcs_bucket_name = "ow-stu-us-ce1-ai-platform"
18
+
19
+ # process of getting credentials
20
+ def get_credentials():
21
+ creds_json_str = os.getenv("BOB") # get json credentials stored as a string
22
+ if creds_json_str is None:
23
+ raise ValueError("GOOGLE_APPLICATION_CREDENTIALS_JSON not found in environment")
24
+
25
+ # create a temporary file
26
+ with tempfile.NamedTemporaryFile(mode="w+", delete=False, suffix=".json") as temp:
27
+ temp.write(creds_json_str) # write in json format
28
+ temp_filename = temp.name
29
+
30
+ return temp_filename
31
+
32
+ # pass
33
+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"]= get_credentials()
34
+
35
+ # Ensure the GCS bucket exists
36
+ gcs_client = storage.Client()
37
+ gcs_bucket = gcs_client.bucket(gcs_bucket_name)
38
+
39
+ # File path in GCS bucket
40
+ gcs_file_path = "deepak_6593/db.csv"
41
+
42
+
43
+ def read_csv(location="chennai"):
44
+ global stop_reading
45
+ global data_location
46
+ global counter
47
+ blob = gcs_bucket.blob(gcs_file_path)
48
+ while not stop_reading:
49
+ file_path = f"https://storage.googleapis.com/dev.openweaver.com/demo/ai/{location}.csv"
50
+ data = pd.read_csv(file_path)
51
+ csv_data = data[0:counter].to_csv(index=False).encode('utf-8')
52
+ blob.upload_from_string(csv_data, content_type='text/csv')
53
+ time.sleep(5)
54
+ counter += 1
55
+
56
+
57
+ def start_reading(location):
58
+ global reading_thread
59
+ reading_thread = Thread(target=read_csv, args=(location,))
60
+ reading_thread.start()
61
+
62
+ def stop_reading_thread():
63
+ global stop_reading
64
+ global reading_thread
65
+ stop_reading = True
66
+ if reading_thread is not None:
67
+ reading_thread.join()
68
+
69
+ @app.get("/update_location/")
70
+ async def update_location(location: str = Query("tambaram")):
71
+ global reading_thread
72
+ global stop_reading
73
+
74
+ if location not in ["tambaram", "velachery"]:
75
+ return {"error": "Invalid location"}
76
+
77
+ if reading_thread is not None and reading_thread.is_alive():
78
+ stop_reading_thread()
79
+
80
+ stop_reading = False
81
+ start_reading(location)
82
+
83
+ return {"message": f"Location updated to {location}"}
84
+
85
+ # if __name__ == "__main__":
86
+ # import uvicorn
87
+
88
+ # uvicorn.run(app, host="0.0.0.0", port=8080)
89
+