Can you generalize this code so it can run on any given csv file? """ def…
- User
Can you generalize this code so it can run on any given csv file?
""" def general_prompt_pipeline(fname, model_k, prompt_k, system_prompt, input_col, out_col): # TODO - generalize this!! df = pd.read_csv(f'{fname}.csv', index_col='tid_order') # head
# if the index isn't unique than re index # the index values should be f"{tid}_{order}" if not df.index.is_unique: df["order"] = df.groupby("Testimony Identifier").cumcount() + 1 df["tid"] = df["Testimony Identifier"].apply(lambda x: str(x).split(".")[-1]) df.index = [f"{tid}_{order}" for tid, order in zip(df["tid"], df["order"])] # output file o_fname = f"outs/{prompt_k}/{model_k}/outs_{fname.split('/')[-1]}_temp_{temperature}" if not ALL_SPLITS: o_fname += "_dev" # if the file exists, read it if Path(f"{o_fname}.csv").exists(): out_df = pd.read_csv(f"{o_fname}.csv", index_col=0) # if any columns are missing, add them - TODO! # add speaker column if it exists in df but not in out_df if "speaker" in df.columns and "speaker" not in out_df.columns: out_df["speaker"] = df["speaker"] # if there are rows in data that are not in out_df, add them new_rows = df[~df.index.isin(out_df.index)] if not new_rows.empty: new_rows[out_col] = np.nan out_df = pd.concat([out_df, new_rows]) # if "split" not in out_df.columns: # out_df["split"] = df["split"] else: out_df = pd.DataFrame(columns=["name", input_col, out_col]) if "filename" in df.columns: out_df['name'] = df.filename.apply(get_name) elif "name" not in out_df.columns: out_df['name'] = df.index out_df[input_col] = df[input_col] if "split" in df.columns: out_df['split'] = df.split if not ALL_SPLITS: out_df = out_df[out_df.split == "dev"] # iterate over each empty sample for index, row in out_df.iterrows(): if pd.isna(row[out_col]): print(f"\n~~ running prompt on sample number {index} ~~\n") response = send_prompt(row[input_col], model_k=model_k, prompt_key=prompt_k, temp=temperature, sys_prompt=system_prompt, ) # save the response # with open(f"outs/{prompt_k}/{model_k}/{index}_{row['name']}.txt", "w") as f: # f.write(str(response.choices[0].message)) out_df.loc[index, out_col] = response.choices[0].message.content # if prompt is DR_ASPECTS then parse the output into a list of keys import ast if prompt_k == "DR_ASPECTS": # parse the output into a list of keys cont = response.choices[0].message.content if not "aspects" in out_df.columns: out_df["aspects"] = None out_df["aspects"] = out_df["aspects"].astype(object) out_df.at[index, "aspects"] = list(ast.literal_eval(cont).keys()) # save the output to the csv file out_df.to_csv(f"{o_fname}.csv") # sleep(1) print(f"Done prompting {model_k} on {prompt_k} for {fname}") - Assistant