deepak6593 commited on
Commit
bd2139a
·
1 Parent(s): ebaba5e
Files changed (1) hide show
  1. main.py +51 -65
main.py CHANGED
@@ -1,14 +1,19 @@
1
- from fastapi import FastAPI, File, UploadFile, Form
2
- from fastapi import APIRouter, Depends, HTTPException, status
3
- import pandas as pd
4
- from google.cloud import storage
5
- import io
6
  import os
 
 
 
7
  import tempfile
8
- from pydantic import BaseModel
9
 
10
  app = FastAPI()
11
 
 
 
 
 
 
12
  gcs_bucket_name = "ow-stu-us-ce1-ai-platform"
13
 
14
  # process of getting credentials
@@ -34,64 +39,45 @@ gcs_bucket = gcs_client.bucket(gcs_bucket_name)
34
  # File path in GCS bucket
35
  gcs_file_path = "deepak_6593/db.csv"
36
 
37
- def append_to_gcs_csv(new_data, gcs_file_path):
38
- # Standardize column names for new data
39
- new_data.columns = ['category', 'score']
40
 
41
- # Check if the file exists in GCS bucket
42
- blob = gcs_bucket.blob(gcs_file_path)
43
- if exists := blob.exists():
44
- existing_data = pd.read_csv(io.BytesIO(blob.download_as_bytes()))
45
- # Ensure existing data has the right columns
46
- existing_data = existing_data[['category', 'score']]
47
- # Append new data to existing data
48
- combined_data = pd.concat([existing_data, new_data], ignore_index=True).dropna(how='all')
49
- else:
50
- combined_data = new_data
51
-
52
- # Convert combined DataFrame to CSV and upload it
53
- csv_data = combined_data.to_csv(index=False).encode('utf-8')
54
- blob.upload_from_string(csv_data, content_type='text/csv')
55
-
56
- def read_from_gcs_csv(gcs_file_path):
57
  blob = gcs_bucket.blob(gcs_file_path)
58
- return pd.read_csv(io.BytesIO(blob.download_as_text()))
59
-
60
- @app.post("/upload-file/")
61
- async def upload_file(file: UploadFile = File(...)):
62
- df = pd.read_csv(io.StringIO((await file.read()).decode('utf-8')))
63
- append_to_gcs_csv(df, gcs_file_path)
64
- return {"message": "File uploaded successfully"}
65
-
66
- @app.post("/upload-data/")
67
- async def upload_data(category: str = Form(...), score: float = Form(...)):
68
- try:
69
- df = pd.DataFrame([[category, score]], columns=['category', 'score'])
70
- append_to_gcs_csv(df, gcs_file_path)
71
- return {"message": "Data uploaded successfully"}
72
- except Exception as e:
73
- raise HTTPException(status_code=422, detail=str(e))
74
-
75
- @app.post("/upload-data-raw/")
76
- async def upload_data_raw(payload: dict):
77
- # sourcery skip: raise-from-previous-error
78
- try:
79
- category = payload['category']
80
- score = payload['score']
81
- except KeyError:
82
- raise HTTPException(status_code=400, detail="Invalid payload format")
83
-
84
- df = pd.DataFrame([[category, score]], columns=['category', 'score'])
85
- append_to_gcs_csv(df, gcs_file_path)
86
- return {"message": "Data uploaded successfully"}
87
-
88
-
89
- @app.post("/clear-data/")
90
- async def clear_data():
91
- # Create an empty DataFrame with the same columns
92
- empty_df = pd.DataFrame(columns=['category', 'score'])
93
- # Convert the empty DataFrame to CSV
94
- csv_data = empty_df.to_csv(index=False).encode('utf-8')
95
- # Overwrite the existing file in GCS with the empty CSV data
96
- gcs_bucket.blob(gcs_file_path).upload_from_string(csv_data, content_type='text/csv')
97
- return {"message": "Data cleared successfully"}
 
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
 
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("chennai")):
71
+ global reading_thread
72
+ global stop_reading
73
+
74
+ if location not in ["chennai", "hyderabad"]:
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}"}