Spaces:
Sleeping
Sleeping
Prod and local env sepearted for logged_data.csv file toa void merge conlfict.
Browse filesFiles changed (4)
- app.py+72-9
- config.pyAdded+35
- config/local.pyAdded+6
- config/production.pyAdded+6
4 unmodified lines567891011129 unmodified lines22232425262735 unmodified lines636465666768697071727374757677784 unmodified linesfrom huggingface_hub import Repositoryimport csvfrom datetime import datetimefrom dotenv import load_dotenvload_dotenv()9 unmodified linesHF_TOKEN = os.environ.get("HF_TOKEN")repo = Repository(local_dir="data", clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN)35 unmodified linesTry to finish each Story point of Story circle in 5 questions or less."""dataset_file_name= "logged_data.csv"callback = gr.CSVLogger(dataset_file_name= dataset_file_name)def store_message_callback(history, feedback):with open(DATA_FILE, "a") as csvfile:writer = csv.DictWriter(csvfile, fieldnames=["time", "history", "feedback"])writer.writerow({"history": history, "feedback": feedback, "time": str(datetime.now())})commit_url = repo.push_to_hub()def predict(message, history, feedback, btn):history.append({"role": "system", "content": system_prompt_1})4 unmodified lines5678910111213149 unmodified lines24252627282930313235 unmodified lines68697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401414 unmodified linesfrom huggingface_hub import Repositoryimport csvfrom datetime import datetimeimport jsonfrom config import get_settingssettings = get_settings()from dotenv import load_dotenvload_dotenv()9 unmodified linesHF_TOKEN = os.environ.get("HF_TOKEN")# Ensure data directory existsos.makedirs("data", exist_ok=True)repo = Repository(local_dir="data", clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN)35 unmodified linesTry to finish each Story point of Story circle in 5 questions or less."""dataset_file_name = settings.DATA_FILEcallback = gr.CSVLogger(dataset_file_name=str(dataset_file_name))def store_message_callback(history, feedback):"""Store conversation history and feedback"""try:# Format conversation historyformatted_history = [{"role": msg["role"], "content": msg["content"]}for msg in historyif isinstance(msg, dict) and "role" in msg and "content" in msg]# Prepare row datarow_data = {"timestamp": datetime.now().isoformat(),"conversation": json.dumps(formatted_history, ensure_ascii=False),"feedback": feedback or ""}# Write to CSVwith open(settings.DATA_FILE, "a", newline='', encoding='utf-8') as csvfile:writer = csv.DictWriter(csvfile, fieldnames=row_data.keys())if csvfile.tell() == 0: # Write header if file is emptywriter.writeheader()writer.writerow(row_data)# Push to hub if in productionif settings.PUSH_TO_HUB:try:repo.git_pull()return repo.push_to_hub()except Exception as e:if settings.DEBUG:print(f"Error pushing to hub: {e}")return Nonereturn Noneexcept Exception as e:if settings.DEBUG:print(f"Error in store_message_callback: {e}")print(f"Attempted to write to: {settings.DATA_FILE}")raise# def store_message_callback(history, feedback):# # Format the data in a cleaner structure# formatted_history = []# for msg in history:# if isinstance(msg, dict) and 'role' in msg and 'content' in msg:# formatted_history.append({# 'role': msg['role'],# 'content': msg['content']# })# # Create timestamp in ISO format# timestamp = datetime.now().isoformat()# # Write to CSV with formatted data# with open(DATA_FILE, "a", newline='') as csvfile:# writer = csv.DictWriter(csvfile, fieldnames=["timestamp", "conversation", "feedback"])# writer.writerow({# "timestamp": timestamp,# "conversation": json.dumps(formatted_history, ensure_ascii=False),# "feedback": feedback if feedback else ""# })# # Push changes to Hugging Face# commit_url = repo.push_to_hub()def predict(message, history, feedback, btn):history.append({"role": "system", "content": system_prompt_1})
1234567891011121314151617181920212223242526272829303132333435# config.pyfrom pathlib import Pathfrom pydantic_settings import BaseSettingsfrom functools import lru_cache
class Settings(BaseSettings): # Base configuration ENVIRONMENT: str = "local" DEBUG: bool = False DATA_DIR: Path = Path("./data") # API Keys and External Services SAMBANOVA_API_KEY: str PUSH_TO_HUB: bool = False # Paths and Files DATA_FILE: Path = DATA_DIR / "logged_data.csv" def __init__(self, **kwargs): super().__init__(**kwargs) # Set data file based on environment if not self.DATA_FILE: self.DATA_FILE = self.DATA_DIR / f"feedback_{self.ENVIRONMENT}.csv" # Ensure data directory exists self.DATA_DIR.mkdir(parents=True, exist_ok=True) class Config: env_file = ".env" env_file_encoding = "utf-8"
@lru_cache()def get_settings(): """Cached settings to avoid reading .env file multiple times""" return Settings()123456# config/local.pyLOCAL_SETTINGS = { "ENVIRONMENT": "local", "DEBUG": True, "PUSH_TO_HUB": False}123456# config/production.pyPRODUCTION_SETTINGS = { "ENVIRONMENT": "production", "DEBUG": False, "PUSH_TO_HUB": True}app.py+72-9
config.pyAdded+35
config/local.pyAdded+6
config/production.pyAdded+6