duongthienz commited on
Commit
6696473
·
verified ·
1 Parent(s): d4b437a

Add Download Multiple file .zip

Browse files
Files changed (1) hide show
  1. state.py +54 -0
state.py CHANGED
@@ -89,6 +89,60 @@ def convert_df(df):
89
  return df.to_csv(index=False).encode("utf-8")
90
 
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  # ---------------------------------------------------------------------------
93
  # Category callbacks
94
  # ---------------------------------------------------------------------------
 
89
  return df.to_csv(index=False).encode("utf-8")
90
 
91
 
92
+ def build_all_csv_zip():
93
+ """Build an in-memory ZIP containing one CSV per analyzed file.
94
+
95
+ Applies the same transformations as the single-file download:
96
+ drop Task, rename Resource -> Speaker, sort by Start, add Role.
97
+ Returns raw ZIP bytes ready for st.download_button.
98
+ """
99
+ import io
100
+ import zipfile
101
+
102
+ buf = io.BytesIO()
103
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
104
+ for fname, result in st.session_state.results.items():
105
+ if len(result) != 2:
106
+ continue
107
+ try:
108
+ annotation, _ = result
109
+ currDF, _ = su.annotationToSimpleDataFrame(annotation)
110
+
111
+ # Apply speaker renames
112
+ renames = st.session_state.speakerRenames.get(fname, {})
113
+ currDF = currDF.copy()
114
+ if "Resource" in currDF.columns:
115
+ currDF["Resource"] = currDF["Resource"].apply(
116
+ lambda s: renames.get(s, s)
117
+ )
118
+
119
+ # Add Role column (raw speaker -> role, before rename applied above,
120
+ # so look up by renamed value since we already applied renames)
121
+ raw_to_role = {
122
+ renames.get(token.split(": ", 1)[1], token.split(": ", 1)[1]):
123
+ st.session_state.categories[i]
124
+ for i, tokens in enumerate(st.session_state.categorySelect)
125
+ for token in tokens
126
+ if token.startswith(f"{fname}: ")
127
+ }
128
+ currDF["Role"] = currDF["Resource"].map(raw_to_role).fillna("")
129
+ currDF = currDF.drop(columns=["Task"], errors="ignore")
130
+ currDF = currDF.rename(columns={"Resource": "Speaker"})
131
+ if "Start" in currDF.columns:
132
+ currDF = currDF.sort_values("Start").reset_index(drop=True)
133
+
134
+ plain_name = fname.rsplit(".", 1)[0]
135
+ zf.writestr(
136
+ f"sonogram-analysis-{plain_name}.csv",
137
+ currDF.to_csv(index=False)
138
+ )
139
+ except Exception as e:
140
+ print(f"build_all_csv_zip: skipping {fname} — {e}")
141
+
142
+ buf.seek(0)
143
+ return buf.read()
144
+
145
+
146
  # ---------------------------------------------------------------------------
147
  # Category callbacks
148
  # ---------------------------------------------------------------------------