Zasha1 commited on
Commit
71c3841
·
verified ·
1 Parent(s): 68b39c8

Update google_sheets.py

Browse files
Files changed (1) hide show
  1. google_sheets.py +86 -85
google_sheets.py CHANGED
@@ -1,85 +1,86 @@
1
- import uuid
2
- from google.oauth2 import service_account
3
- from googleapiclient.discovery import build
4
- from env_setup import config
5
- import pandas as pd
6
-
7
- SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
8
-
9
- def authenticate_google_account():
10
- service_account_file = config["google_creds"]
11
- if not service_account_file:
12
- raise ValueError("Service account credentials path is missing in env_setup.py.")
13
- return service_account.Credentials.from_service_account_file(service_account_file, scopes=SCOPES)
14
-
15
- def store_data_in_sheet(sheet_id, chunks, summary, overall_sentiment):
16
- creds = authenticate_google_account()
17
- service = build('sheets', 'v4', credentials=creds)
18
- sheet = service.spreadsheets()
19
-
20
- call_id = str(uuid.uuid4())
21
- print(f"Call ID: {call_id}")
22
-
23
- values = []
24
- if chunks:
25
- first_chunk, first_sentiment, _ = chunks[0]
26
- values.append([call_id, first_chunk, first_sentiment, summary, overall_sentiment])
27
- for chunk, sentiment, _ in chunks[1:]:
28
- values.append(["", chunk, sentiment, "", ""])
29
-
30
- header = ["Call ID", "Chunk", "Sentiment", "Summary", "Overall Sentiment"]
31
- all_values = [header] + values
32
-
33
- body = {'values': all_values}
34
- try:
35
- result = sheet.values().append(
36
- spreadsheetId=sheet_id,
37
- range="Sheet1!A1",
38
- valueInputOption="RAW",
39
- body=body
40
- ).execute()
41
- print(f"{result.get('updates').get('updatedCells')} cells updated in Google Sheets.")
42
- except Exception as e:
43
- print(f"Error updating Google Sheets: {e}")
44
-
45
- def fetch_call_data(sheet_id, sheet_range="Sheet1!A1:E"):
46
- """
47
- Fetches data from the specified Google Sheet and returns a pandas DataFrame.
48
-
49
- :param sheet_id: The ID of the Google Sheet to fetch data from.
50
- :param sheet_range: The range in A1 notation to fetch data from.
51
- :return: pandas DataFrame with the sheet data.
52
- """
53
- try:
54
- # Authenticate and get credentials
55
- creds = authenticate_google_account()
56
- service = build('sheets', 'v4', credentials=creds)
57
- sheet = service.spreadsheets()
58
-
59
- # Fetch the data
60
- result = sheet.values().get(
61
- spreadsheetId=sheet_id,
62
- range=sheet_range
63
- ).execute()
64
-
65
- # Get the rows
66
- rows = result.get("values", [])
67
-
68
- # If rows exist, convert to DataFrame
69
- if rows:
70
- # Use the first row as column headers
71
- headers = rows[0]
72
- data = rows[1:]
73
-
74
- # Create DataFrame
75
- df = pd.DataFrame(data, columns=headers)
76
-
77
- return df
78
- else:
79
- # Return an empty DataFrame if no data
80
- return pd.DataFrame()
81
-
82
- except Exception as e:
83
- print(f"Error fetching data from Google Sheets: {e}")
84
- # Return an empty DataFrame in case of error
85
- return pd.DataFrame()
 
 
1
+ import uuid
2
+ from google.oauth2 import service_account
3
+ from googleapiclient.discovery import build
4
+ from env_setup import config
5
+ import pandas as pd
6
+
7
+ # Define the required scopes for accessing Google Sheets
8
+ SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
9
+
10
+ def authenticate_google_account():
11
+ """
12
+ Authenticate the Google account using service account credentials.
13
+ """
14
+ service_account_file = config["google_creds"]
15
+ if not service_account_file:
16
+ raise ValueError("Service account credentials path is missing in env_setup.py.")
17
+ return service_account.Credentials.from_service_account_file(service_account_file, scopes=SCOPES)
18
+
19
+ def store_data_in_sheet(sheet_id, chunks, summary, overall_sentiment):
20
+ """
21
+ Store data into a Google Sheet.
22
+ """
23
+ creds = authenticate_google_account()
24
+ service = build('sheets', 'v4', credentials=creds)
25
+ sheet = service.spreadsheets()
26
+
27
+ call_id = str(uuid.uuid4())
28
+ print(f"Call ID: {call_id}")
29
+
30
+ values = []
31
+ if chunks:
32
+ first_chunk, first_sentiment, _ = chunks[0]
33
+ values.append([call_id, first_chunk, first_sentiment, summary, overall_sentiment])
34
+ for chunk, sentiment, _ in chunks[1:]:
35
+ values.append(["", chunk, sentiment, "", ""])
36
+
37
+ header = ["Call ID", "Chunk", "Sentiment", "Summary", "Overall Sentiment"]
38
+ all_values = [header] + values
39
+
40
+ body = {'values': all_values}
41
+ try:
42
+ result = sheet.values().append(
43
+ spreadsheetId=sheet_id,
44
+ range="Sheet1!A1",
45
+ valueInputOption="RAW",
46
+ body=body
47
+ ).execute()
48
+ print(f"{result.get('updates').get('updatedCells')} cells updated in Google Sheets.")
49
+ except Exception as e:
50
+ print(f"Error updating Google Sheets: {e}")
51
+
52
+ def fetch_call_data(sheet_id, sheet_range="Sheet1!A1:E"):
53
+ """
54
+ Fetches data from the specified Google Sheet and returns a pandas DataFrame.
55
+ """
56
+ try:
57
+ # Authenticate and get credentials
58
+ creds = authenticate_google_account()
59
+ service = build('sheets', 'v4', credentials=creds)
60
+ sheet = service.spreadsheets()
61
+
62
+ # Fetch the data
63
+ result = sheet.values().get(
64
+ spreadsheetId=sheet_id,
65
+ range=sheet_range
66
+ ).execute()
67
+
68
+ # Get the rows
69
+ rows = result.get("values", [])
70
+
71
+ # If rows exist, convert to DataFrame
72
+ if rows:
73
+ headers = rows[0]
74
+ data = rows[1:]
75
+ if not data:
76
+ print("No data available in the specified range.")
77
+ return pd.DataFrame(columns=headers) # Return DataFrame with headers only
78
+ df = pd.DataFrame(data, columns=headers)
79
+ return df
80
+ else:
81
+ print("No data available in the Google Sheet.")
82
+ return pd.DataFrame()
83
+
84
+ except Exception as e:
85
+ print(f"Error fetching data from Google Sheets: {e}")
86
+ return pd.DataFrame()