nachoremer commited on
Commit
f05bf99
·
1 Parent(s): 383a1f0

cambio a atlas

Browse files
Files changed (2) hide show
  1. app.py +13 -59
  2. config.py +17 -0
app.py CHANGED
@@ -5,7 +5,7 @@ import gradio as gr
5
  import pandas as pd
6
  from datetime import datetime, timedelta, timezone
7
  #import torch
8
- from config import groq_token, groq_model, QUESTION_PROMPT, init_google_sheets_client, groq_model, default_model_name, user_names, google_sheets_name
9
 
10
  #from config import hugging_face_token, replicate_token
11
  #import replicate
@@ -74,64 +74,18 @@ model_history = []
74
  # Save all_answers to Google Drive
75
  FILE_ID = '1PwEiBxpHo0jRc6T1HixyC99UnP9iawbr'
76
 
 
 
77
 
78
- def save_answers(all_answers):
79
- # Credenciales de la cuenta de servicio (reemplaza con tus credenciales)
80
- SCOPES = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
81
- SERVICE_ACCOUNT_FILE = 'polar-land-440713-c4-bbc8d89804d8.json'
82
- # Autentificación
83
- credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
84
- service = build('drive', 'v3', credentials=credentials)
85
-
86
- # Obtener el archivo existente
87
- file = service.files().get(fileId=FILE_ID).execute()
88
-
89
- # Download the content using get_media instead of export_media
90
- request = service.files().get_media(fileId=FILE_ID)
91
- fh = io.BytesIO()
92
- downloader = MediaIoBaseDownload(fh, request)
93
- done = False
94
- while done is False:
95
- status, done = downloader.next_chunk()
96
- print("Download %d%%." % int(status.progress() * 100))
97
-
98
- # Cargar el contenido JSON
99
- content = fh.getvalue()
100
- if content:
101
- existing_data = json.loads(content)
102
- else:
103
- existing_data = {}
104
-
105
- # Convert sets to lists before serialization if they exist
106
- def convert_sets_to_lists(obj):
107
- if isinstance(obj, set):
108
- return list(obj)
109
- if isinstance(obj, dict):
110
- return {k: convert_sets_to_lists(v) for k, v in obj.items()}
111
- if isinstance(obj, list):
112
- return [convert_sets_to_lists(item) for item in obj]
113
- return obj
114
-
115
- existing_data = convert_sets_to_lists(existing_data)
116
-
117
- # Agregar los nuevos datos al arreglo
118
- if 'data' in existing_data:
119
- existing_data['data'].append(all_answers)
120
- else:
121
- existing_data['data'] = [all_answers]
122
- # Convertir los datos a formato JSON
123
- new_content = json.dumps(existing_data)
124
-
125
- # Create a temporary file to store the JSON data
126
- with open('temp_data.json', 'w') as temp_file:
127
- temp_file.write(new_content)
128
-
129
- media = MediaFileUpload('temp_data.json', mimetype='application/json')
130
- file = service.files().update(fileId=FILE_ID,
131
- media_body=media,
132
- fields='id').execute()
133
- print('Archivo actualizado correctamente: %s' % file.get('id'))
134
 
 
 
 
 
 
 
 
 
135
 
136
 
137
  #Function to save comment and score
@@ -175,9 +129,9 @@ def save_comment_score(score, comment, story_name, user_name, system_prompt, mod
175
  user_sheet.append_row([timestamp_str, user_name, model_name, system_prompt, story_name, full_chat_history, score, comment])
176
 
177
 
178
- # Save all answers to Google Drive as a JSON file
179
  print(f"all answers...\n{all_answers}")
180
- save_answers(all_answers)
181
 
182
  #Append data and render the data table
183
  df = pd.DataFrame(data, columns=["Timestamp", "User Name", "Model Name", "System Prompt", "Story Name", "Chat History", "Score", "Comment"])
 
5
  import pandas as pd
6
  from datetime import datetime, timedelta, timezone
7
  #import torch
8
+ from config import groq_token, groq_model, QUESTION_PROMPT, init_google_sheets_client, groq_model, default_model_name, user_names, google_sheets_name, AtlasClient
9
 
10
  #from config import hugging_face_token, replicate_token
11
  #import replicate
 
74
  # Save all_answers to Google Drive
75
  FILE_ID = '1PwEiBxpHo0jRc6T1HixyC99UnP9iawbr'
76
 
77
+ #init atlas client
78
+ atlas_client = AtlasClient("chatbot_test")
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ def save_answers(all_answers, user_name):
82
+ timestamp = datetime.now(timezone.utc) - timedelta(hours=3) # Adjust to GMT-3
83
+ timestamp_str = timestamp.strftime("%Y-%m-%d %H:%M:%S")
84
+ data = {}
85
+ data["timestamp"] = timestamp_str
86
+ data["answers"] = all_answers
87
+ data['author'] = user_name
88
+ atlas_client.add(data, "dialogs")
89
 
90
 
91
  #Function to save comment and score
 
129
  user_sheet.append_row([timestamp_str, user_name, model_name, system_prompt, story_name, full_chat_history, score, comment])
130
 
131
 
132
+ # Save all answers to AtlaS collection
133
  print(f"all answers...\n{all_answers}")
134
+ save_answers(all_answers, user_name)
135
 
136
  #Append data and render the data table
137
  df = pd.DataFrame(data, columns=["Timestamp", "User Name", "Model Name", "System Prompt", "Story Name", "Chat History", "Score", "Comment"])
config.py CHANGED
@@ -1,11 +1,28 @@
1
  import os
2
  import gspread
3
  from oauth2client.service_account import ServiceAccountCredentials
 
4
 
5
  # Read the authentication token from the environment variable
6
  hugging_face_token = os.getenv("HUGGING_FACE_TOKEN")
7
  replicate_token = os.getenv("REPLICATE_TOKEN")
8
  groq_token = os.getenv("GROQ_TOKEN")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  # Google Sheets configuration
11
  def init_google_sheets_client():
 
1
  import os
2
  import gspread
3
  from oauth2client.service_account import ServiceAccountCredentials
4
+ from pymongo import MongoClient
5
 
6
  # Read the authentication token from the environment variable
7
  hugging_face_token = os.getenv("HUGGING_FACE_TOKEN")
8
  replicate_token = os.getenv("REPLICATE_TOKEN")
9
  groq_token = os.getenv("GROQ_TOKEN")
10
+ atlas_token = os.getenv("ATLAS_TOKEN")
11
+
12
+ #atlas configuration
13
+ class AtlasClient:
14
+ def __init__(self, dbname):
15
+ self.mongodb_client = MongoClient(atlas_token)
16
+ self.database = self.mongodb_client[dbname]
17
+
18
+ # A quick way to test if we can connect to Atlas instance
19
+ def ping(self):
20
+ self.mongodb_client.admin.command("ping")
21
+
22
+
23
+ def add(self, item, collection_name):
24
+ collection = self.database[collection_name]
25
+ collection.insert_one(item)
26
 
27
  # Google Sheets configuration
28
  def init_google_sheets_client():