geekgirl3 commited on
Commit
02a5847
·
verified ·
1 Parent(s): bd3e2ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -762
app.py CHANGED
@@ -700,765 +700,4 @@ with gr.Blocks(title="Binary Matrix Feedback Transformer", css="""
700
 
701
  # Launch the app
702
  if __name__ == "__main__":
703
- demo.launch(import gradio as gr
704
- import pandas as pd
705
- import numpy as np
706
- import os
707
- import traceback
708
- from typing import Tuple, Dict, Any, Optional, List
709
- import tempfile
710
- import io
711
- import datetime
712
- import re
713
-
714
- class FeedbackTransformer:
715
- """
716
- A class to transform feedback data with delimited topic and sentiment columns
717
- into binary columns with prefixes T_, S_, and C_.
718
- """
719
-
720
- def __init__(self,
721
- topic_prefix="TOPIC_",
722
- sentiment_prefix="SENTIMENT_",
723
- category_prefix="Categories:",
724
- text_column="TEXT",
725
- recommendation_column="Q4_Weiterempfehlung"):
726
- """
727
- Initialize the FeedbackTransformer with column specifications.
728
- """
729
- self.topic_prefix = topic_prefix
730
- self.sentiment_prefix = sentiment_prefix
731
- self.category_prefix = category_prefix
732
- self.text_column = text_column
733
- self.recommendation_column = recommendation_column
734
- self.data = None
735
- self.transformed_data = None
736
- self.topic_cols = []
737
- self.sentiment_cols = []
738
- self.category_cols = []
739
- self.unique_topics = set()
740
- self.unique_categories = set()
741
- self.unique_sentiments = set()
742
- self.topic_sentiment_mapping = {} # Map topics to their sentiment values
743
- self.file_name = None
744
- self.original_filename = None
745
- self.selected_columns = []
746
- self.verbatim_column = None # Store the verbatim/text column
747
- self.dynamic_topic_prefix = None # Store dynamically extracted topic prefix
748
-
749
- def load_data(self, file_obj):
750
- """
751
- Load data from the uploaded file object.
752
- """
753
- if file_obj is None:
754
- raise ValueError("No file uploaded")
755
-
756
- # Get file extension and store original filename
757
- file_name = file_obj if isinstance(file_obj, str) else (file_obj.name if hasattr(file_obj, 'name') else 'unknown')
758
- self.original_filename = os.path.splitext(os.path.basename(file_name))[0]
759
- _, file_ext = os.path.splitext(file_name)
760
-
761
- # Read the data based on file type
762
- try:
763
- if file_ext.lower() in ['.xlsx', '.xls']:
764
- self.data = pd.read_excel(file_obj)
765
- elif file_ext.lower() == '.csv':
766
- # Try comma delimiter first
767
- try:
768
- self.data = pd.read_csv(file_obj, encoding='utf-8')
769
- except:
770
- # If comma fails, try tab delimiter
771
- self.data = pd.read_csv(file_obj, sep='\t', encoding='utf-8')
772
- else:
773
- # Default to tab-delimited
774
- self.data = pd.read_csv(file_obj, sep='\t', encoding='utf-8')
775
- except Exception as e:
776
- raise ValueError(f"Error reading file: {str(e)}")
777
-
778
- return len(self.data), len(self.data.columns)
779
-
780
- def extract_topic_prefix_from_category(self):
781
- """
782
- Extract the topic prefix from a column containing "Category:"
783
- by finding text between "Category:" and "("
784
- """
785
- # Look for columns containing "Category:"
786
- category_pattern_cols = [col for col in self.data.columns if "Category:" in col]
787
-
788
- if category_pattern_cols:
789
- # Use the first matching column
790
- category_col = category_pattern_cols[0]
791
-
792
- # Try to extract from column name first
793
- match = re.search(r'Category:\s*([^(]+)\s*\(', category_col)
794
- if match:
795
- extracted_prefix = match.group(1).strip() + ":"
796
- self.dynamic_topic_prefix = extracted_prefix
797
- return extracted_prefix
798
-
799
- # If not found in column name, try to extract from column values
800
- for value in self.data[category_col].dropna():
801
- if isinstance(value, str):
802
- match = re.search(r'Category:\s*([^(]+)\s*\(', value)
803
- if match:
804
- extracted_prefix = match.group(1).strip() + ":"
805
- self.dynamic_topic_prefix = extracted_prefix
806
- return extracted_prefix
807
-
808
- # If no match found, return None
809
- return None
810
-
811
- def identify_columns(self):
812
- """
813
- Identify topic, category, and sentiment columns in the data.
814
- """
815
- if self.data is None:
816
- raise ValueError("Data not loaded")
817
-
818
- # First try to extract topic prefix dynamically
819
- extracted_prefix = self.extract_topic_prefix_from_category()
820
-
821
- # Use dynamic prefix if found, otherwise use the provided topic_prefix
822
- topic_identifier = extracted_prefix if extracted_prefix else self.topic_prefix
823
-
824
- # Log the prefix being used
825
- print(f"Using topic prefix: '{topic_identifier}'")
826
-
827
- # Extract columns based on prefixes
828
- # For topic columns, use the dynamic or provided prefix
829
- if topic_identifier:
830
- self.topic_cols = [col for col in self.data.columns if topic_identifier in col]
831
- else:
832
- self.topic_cols = [col for col in self.data.columns if "Topic:" in col]
833
-
834
- self.sentiment_cols = [col for col in self.data.columns if self.sentiment_prefix in col]
835
- self.category_cols = [col for col in self.data.columns if col.startswith(self.category_prefix)]
836
-
837
- # Try to identify verbatim/text column
838
- text_candidates = [col for col in self.data.columns if any(keyword in col.lower() for keyword in ['text', 'verbatim', 'comment', 'feedback'])]
839
- if text_candidates:
840
- self.verbatim_column = text_candidates[0] # Use the first match
841
- elif self.text_column in self.data.columns:
842
- self.verbatim_column = self.text_column
843
-
844
- # If no columns found with specified prefixes, return all columns for manual selection
845
- all_cols = list(self.data.columns)
846
-
847
- return {
848
- 'topic_cols': self.topic_cols,
849
- 'sentiment_cols': self.sentiment_cols,
850
- 'category_cols': self.category_cols,
851
- 'all_columns': all_cols,
852
- 'verbatim_column': self.verbatim_column,
853
- 'dynamic_topic_prefix': self.dynamic_topic_prefix
854
- }
855
-
856
- def extract_unique_topics_and_categories(self):
857
- """
858
- Extract all unique topics, categories, and sentiments from the respective columns.
859
- """
860
- self.unique_topics = set()
861
- self.unique_categories = set()
862
- self.unique_sentiments = set()
863
- self.topic_sentiment_mapping = {}
864
-
865
- # Extract from topic columns (delimited by |)
866
- for col in self.topic_cols:
867
- for value in self.data[col].dropna():
868
- if isinstance(value, str) and value.strip():
869
- # Split by | delimiter and clean each topic
870
- topics = [topic.strip() for topic in value.split('|') if topic.strip()]
871
- self.unique_topics.update(topics)
872
-
873
- # Extract from category columns (delimited by |)
874
- for col in self.category_cols:
875
- for value in self.data[col].dropna():
876
- if isinstance(value, str) and value.strip():
877
- # Split by | delimiter and clean each category
878
- categories = [cat.strip() for cat in value.split('|') if cat.strip()]
879
- self.unique_categories.update(categories)
880
-
881
- # Extract sentiments from sentiment columns and build topic-sentiment mapping
882
- for col in self.sentiment_cols:
883
- for idx, value in enumerate(self.data[col].dropna()):
884
- if isinstance(value, str) and value.strip():
885
- # Split by | delimiter to get individual topic::sentiment pairs
886
- pairs = [pair.strip() for pair in value.split('|') if pair.strip() and '::' in pair]
887
- for pair in pairs:
888
- if '::' in pair:
889
- topic_part, sentiment_part = pair.split('::', 1)
890
- topic = topic_part.strip()
891
- sentiment = sentiment_part.strip()
892
- if topic and sentiment:
893
- self.unique_topics.add(topic) # Add topic from sentiment data
894
- self.unique_sentiments.add(sentiment)
895
-
896
- # Store the mapping for later use
897
- if idx not in self.topic_sentiment_mapping:
898
- self.topic_sentiment_mapping[idx] = {}
899
- self.topic_sentiment_mapping[idx][topic] = sentiment
900
-
901
- return len(self.unique_topics), len(self.unique_categories), len(self.unique_sentiments)
902
-
903
- def set_selected_columns(self, selected_columns):
904
- """
905
- Set which original columns should be included in the output.
906
- """
907
- self.selected_columns = selected_columns if selected_columns else []
908
-
909
- def transform_data(self):
910
- """
911
- Transform the data into binary columns with T_, S_, and C_ prefixes.
912
- """
913
- if not self.unique_topics and not self.unique_categories:
914
- self.extract_unique_topics_and_categories()
915
-
916
- # Create output dataframe starting with feedback_id
917
- self.transformed_data = pd.DataFrame({'feedback_id': range(1, len(self.data) + 1)})
918
-
919
- # Add selected original columns first (right after feedback_id)
920
- for col in self.selected_columns:
921
- if col in self.data.columns:
922
- self.transformed_data[col] = self.data[col]
923
-
924
- # Add Verbatim sentiment columns
925
- self.transformed_data['Verbatim_Positive'] = 0
926
- self.transformed_data['Verbatim_Neutral'] = 0
927
- self.transformed_data['Verbatim_Negative'] = 0
928
-
929
- # Create binary topic columns with T_ prefix
930
- for topic in sorted(self.unique_topics):
931
- safe_topic_name = self._make_safe_column_name(topic)
932
- col_name = f"T_{safe_topic_name}"
933
- self.transformed_data[col_name] = 0
934
-
935
- # Create sentiment columns with S_ prefix (one per topic, containing actual sentiment values)
936
- for topic in sorted(self.unique_topics):
937
- safe_topic_name = self._make_safe_column_name(topic)
938
- col_name = f"S_{safe_topic_name}"
939
- self.transformed_data[col_name] = "" # Initialize with empty strings
940
-
941
- # Create binary category columns with C_ prefix
942
- for category in sorted(self.unique_categories):
943
- safe_category_name = self._make_safe_column_name(category)
944
- col_name = f"C_{safe_category_name}"
945
- self.transformed_data[col_name] = 0
946
-
947
- # Fill in the data
948
- for idx, row in self.data.iterrows():
949
- # Process sentiment columns to determine which topics exist in ABSA column
950
- topics_in_absa = set()
951
- all_sentiments_in_row = set() # Track all sentiments for verbatim columns
952
-
953
- for s_col in self.sentiment_cols:
954
- sentiment_value = row.get(s_col)
955
- if pd.notna(sentiment_value) and isinstance(sentiment_value, str) and sentiment_value.strip():
956
- pairs = [pair.strip() for pair in sentiment_value.split('|') if pair.strip()]
957
- for pair in pairs:
958
- if '::' in pair:
959
- topic_part, sentiment_part = pair.split('::', 1)
960
- topic = topic_part.strip()
961
- sentiment = sentiment_part.strip()
962
-
963
- if topic and sentiment:
964
- topics_in_absa.add(topic)
965
- all_sentiments_in_row.add(sentiment.lower()) # Store in lowercase for matching
966
-
967
- # Set the actual sentiment value (not 1/0)
968
- safe_topic_name = self._make_safe_column_name(topic)
969
- sentiment_col_name = f"S_{safe_topic_name}"
970
- if sentiment_col_name in self.transformed_data.columns:
971
- self.transformed_data.loc[idx, sentiment_col_name] = sentiment
972
-
973
- # Set Verbatim sentiment columns based on sentiments found in ABSA
974
- if any(sentiment in all_sentiments_in_row for sentiment in ['positive', 'positiv']):
975
- self.transformed_data.loc[idx, 'Verbatim_Positive'] = 1
976
- if any(sentiment in all_sentiments_in_row for sentiment in ['neutral']):
977
- self.transformed_data.loc[idx, 'Verbatim_Neutral'] = 1
978
- if any(sentiment in all_sentiments_in_row for sentiment in ['negative', 'negativ']):
979
- self.transformed_data.loc[idx, 'Verbatim_Negative'] = 1
980
-
981
- # Set T_ columns to 1 if topic exists in ABSA column, 0 otherwise
982
- for topic in topics_in_absa:
983
- safe_topic_name = self._make_safe_column_name(topic)
984
- topic_col_name = f"T_{safe_topic_name}"
985
- if topic_col_name in self.transformed_data.columns:
986
- self.transformed_data.loc[idx, topic_col_name] = 1
987
-
988
- # Process category columns
989
- categories_in_row = set()
990
- for c_col in self.category_cols:
991
- category_value = row.get(c_col)
992
- if pd.notna(category_value) and isinstance(category_value, str) and category_value.strip():
993
- categories = [cat.strip() for cat in category_value.split('|') if cat.strip()]
994
- categories_in_row.update(categories)
995
-
996
- # Set category binary values (always 1 if present in category column)
997
- for category in categories_in_row:
998
- safe_category_name = self._make_safe_column_name(category)
999
- category_col_name = f"C_{safe_category_name}"
1000
- if category_col_name in self.transformed_data.columns:
1001
- self.transformed_data.loc[idx, category_col_name] = 1
1002
-
1003
- return self.transformed_data.shape
1004
-
1005
- def _make_safe_column_name(self, name):
1006
- """
1007
- Convert a name to a safe column name by removing/replacing problematic characters.
1008
- """
1009
- # Replace spaces and special characters with underscores
1010
- safe_name = re.sub(r'[^\w]', '_', str(name))
1011
- # Remove multiple consecutive underscores
1012
- safe_name = re.sub(r'_+', '_', safe_name)
1013
- # Remove leading/trailing underscores
1014
- safe_name = safe_name.strip('_')
1015
- return safe_name
1016
-
1017
- def analyze_data(self):
1018
- """
1019
- Analyze the transformed data to provide insights.
1020
- """
1021
- if self.transformed_data is None:
1022
- raise ValueError("No transformed data to analyze")
1023
-
1024
- # Count different types of columns
1025
- topic_cols = [col for col in self.transformed_data.columns if col.startswith('T_')]
1026
- sentiment_cols = [col for col in self.transformed_data.columns if col.startswith('S_')]
1027
- category_cols = [col for col in self.transformed_data.columns if col.startswith('C_')]
1028
- verbatim_cols = ['Verbatim_Positive', 'Verbatim_Neutral', 'Verbatim_Negative']
1029
-
1030
- # Calculate statistics
1031
- topic_stats = {}
1032
- for col in topic_cols:
1033
- topic_stats[col] = self.transformed_data[col].sum()
1034
-
1035
- # For sentiment columns, count non-empty values
1036
- sentiment_stats = {}
1037
- for col in sentiment_cols:
1038
- sentiment_stats[col] = (self.transformed_data[col] != "").sum()
1039
-
1040
- category_stats = {}
1041
- for col in category_cols:
1042
- category_stats[col] = self.transformed_data[col].sum()
1043
-
1044
- # Verbatim sentiment statistics
1045
- verbatim_stats = {}
1046
- for col in verbatim_cols:
1047
- if col in self.transformed_data.columns:
1048
- verbatim_stats[col] = self.transformed_data[col].sum()
1049
-
1050
- # Sort by frequency
1051
- sorted_topics = sorted(topic_stats.items(), key=lambda x: x[1], reverse=True)
1052
- sorted_sentiments = sorted(sentiment_stats.items(), key=lambda x: x[1], reverse=True)
1053
- sorted_categories = sorted(category_stats.items(), key=lambda x: x[1], reverse=True)
1054
- sorted_verbatim = sorted(verbatim_stats.items(), key=lambda x: x[1], reverse=True)
1055
-
1056
- # Prepare analysis summary
1057
- analysis_text = f"**Analysis Results**\n\n"
1058
- analysis_text += f"Total feedbacks: {len(self.transformed_data)}\n"
1059
- analysis_text += f"Selected original columns: {len(self.selected_columns)}\n"
1060
- analysis_text += f"Verbatim sentiment columns: 3 (Positive, Neutral, Negative)\n"
1061
- analysis_text += f"Topic columns (T_): {len(topic_cols)}\n"
1062
- analysis_text += f"Sentiment columns (S_): {len(sentiment_cols)}\n"
1063
- analysis_text += f"Category columns (C_): {len(category_cols)}\n"
1064
- analysis_text += f"Verbatim column used: {self.verbatim_column}\n"
1065
-
1066
- # Add dynamic topic prefix info
1067
- if self.dynamic_topic_prefix:
1068
- analysis_text += f"Dynamic topic prefix extracted: '{self.dynamic_topic_prefix}'\n\n"
1069
- else:
1070
- analysis_text += f"Topic prefix used: '{self.topic_prefix}'\n\n"
1071
-
1072
- if self.selected_columns:
1073
- analysis_text += f"**Included Original Columns:** {', '.join(self.selected_columns)}\n\n"
1074
-
1075
- # Verbatim sentiment analysis
1076
- if sorted_verbatim:
1077
- analysis_text += "**Verbatim Sentiment Distribution:**\n"
1078
- for verbatim_col, count in sorted_verbatim:
1079
- percentage = (count / len(self.transformed_data)) * 100
1080
- analysis_text += f"- {verbatim_col}: {count} occurrences ({percentage:.1f}%)\n"
1081
-
1082
- # Topic analysis
1083
- if sorted_topics:
1084
- analysis_text += "\n**Top 10 Most Frequent Topics (T_):**\n"
1085
- for topic_col, count in sorted_topics[:10]:
1086
- analysis_text += f"- {topic_col}: {count} occurrences\n"
1087
-
1088
- # Category analysis
1089
- if sorted_categories:
1090
- analysis_text += "\n**Top 10 Most Frequent Categories (C_):**\n"
1091
- for category_col, count in sorted_categories[:10]:
1092
- analysis_text += f"- {category_col}: {count} occurrences\n"
1093
-
1094
- # Sentiment analysis
1095
- if sorted_sentiments:
1096
- analysis_text += "\n**Top 10 Most Frequent Sentiments (S_):**\n"
1097
- for sentiment_col, count in sorted_sentiments[:10]:
1098
- analysis_text += f"- {sentiment_col}: {count} sentiment values\n"
1099
-
1100
- return analysis_text
1101
-
1102
- def save_transformed_data(self, output_format='xlsx'):
1103
- """
1104
- Save the transformed data and return the file path.
1105
- """
1106
- if self.transformed_data is None:
1107
- raise ValueError("No transformed data to save")
1108
-
1109
- # Create filename with original filename prefix and timestamp
1110
- timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
1111
- prefix = self.original_filename if self.original_filename else 'transformed_feedback'
1112
-
1113
- if output_format == 'xlsx':
1114
- filename = f"{prefix}_transformed_topics_{timestamp}.xlsx"
1115
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx')
1116
- self.transformed_data.to_excel(temp_file.name, index=False)
1117
- temp_file.close()
1118
-
1119
- final_path = os.path.join(tempfile.gettempdir(), filename)
1120
- if os.path.exists(final_path):
1121
- os.remove(final_path)
1122
- os.rename(temp_file.name, final_path)
1123
-
1124
- else: # csv
1125
- filename = f"{prefix}_binary_matrix_{timestamp}.csv"
1126
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.csv')
1127
- self.transformed_data.to_csv(temp_file.name, index=False)
1128
- temp_file.close()
1129
-
1130
- final_path = os.path.join(tempfile.gettempdir(), filename)
1131
- if os.path.exists(final_path):
1132
- os.remove(final_path)
1133
- os.rename(temp_file.name, final_path)
1134
-
1135
- if not os.path.exists(final_path):
1136
- raise ValueError(f"Failed to create output file: {final_path}")
1137
-
1138
- return final_path
1139
-
1140
-
1141
- # Gradio interface functions
1142
- def get_column_selector(file_obj):
1143
- """
1144
- Get a combined column preview and selector interface.
1145
- """
1146
- try:
1147
- if file_obj is None:
1148
- return gr.CheckboxGroup(
1149
- choices=[],
1150
- value=[],
1151
- label="📋 Select Columns to Include",
1152
- info="Upload a file first to see available columns"
1153
- )
1154
-
1155
- # Read first few rows to get column names
1156
- file_name = file_obj if isinstance(file_obj, str) else (file_obj.name if hasattr(file_obj, 'name') else 'unknown')
1157
- _, file_ext = os.path.splitext(file_name)
1158
-
1159
- if file_ext.lower() in ['.xlsx', '.xls']:
1160
- df = pd.read_excel(file_obj, nrows=5)
1161
- elif file_ext.lower() == '.csv':
1162
- try:
1163
- df = pd.read_csv(file_obj, nrows=5)
1164
- except:
1165
- df = pd.read_csv(file_obj, sep='\t', nrows=5)
1166
- else:
1167
- df = pd.read_csv(file_obj, sep='\t', nrows=5)
1168
-
1169
- columns = list(df.columns)
1170
- column_choices = [f"{i+1:2d}. {col}" for i, col in enumerate(columns)]
1171
-
1172
- return gr.CheckboxGroup(
1173
- choices=column_choices,
1174
- value=[],
1175
- label=f"📋 Select Columns to Include ({len(columns)} available)",
1176
- info="Choose which original columns to include in the transformed file (in addition to feedback_id).",
1177
- elem_classes=["column-selector"]
1178
- )
1179
-
1180
- except Exception as e:
1181
- return gr.CheckboxGroup(
1182
- choices=[],
1183
- value=[],
1184
- label="📋 Select Columns to Include",
1185
- info=f"Error reading file: {str(e)}"
1186
- )
1187
-
1188
-
1189
- def extract_column_names(selected_display_names):
1190
- """
1191
- Extract actual column names from the numbered display format.
1192
- """
1193
- if not selected_display_names:
1194
- return []
1195
-
1196
- actual_names = []
1197
- for display_name in selected_display_names:
1198
- if '. ' in display_name:
1199
- actual_name = display_name.split('. ', 1)[1]
1200
- actual_names.append(actual_name)
1201
- else:
1202
- actual_names.append(display_name)
1203
-
1204
- return actual_names
1205
-
1206
-
1207
- def process_file(file_obj, topic_prefix, sentiment_prefix, category_prefix,
1208
- text_column, recommendation_column, output_format, analyze_data, selected_columns):
1209
- """
1210
- Main processing function for Gradio interface.
1211
- """
1212
- try:
1213
- # Extract actual column names from display format
1214
- actual_column_names = extract_column_names(selected_columns)
1215
-
1216
- # Initialize transformer
1217
- transformer = FeedbackTransformer(
1218
- topic_prefix=topic_prefix,
1219
- sentiment_prefix=sentiment_prefix,
1220
- category_prefix=category_prefix,
1221
- text_column=text_column,
1222
- recommendation_column=recommendation_column
1223
- )
1224
-
1225
- # Load data
1226
- rows, cols = transformer.load_data(file_obj)
1227
- status_msg = f"✅ Loaded {rows} rows and {cols} columns\n"
1228
-
1229
- # Set selected columns for inclusion
1230
- transformer.set_selected_columns(actual_column_names)
1231
- status_msg += f"📋 Selected {len(actual_column_names)} original columns for inclusion\n"
1232
- if actual_column_names:
1233
- status_msg += f" Selected columns: {', '.join(actual_column_names)}\n"
1234
-
1235
- # Identify columns
1236
- col_info = transformer.identify_columns()
1237
- status_msg += f"\n📊 Found columns:\n"
1238
- status_msg += f"- Topic columns: {len(col_info['topic_cols'])}\n"
1239
- status_msg += f"- Sentiment columns: {len(col_info['sentiment_cols'])}\n"
1240
- status_msg += f"- Category columns: {len(col_info['category_cols'])}\n"
1241
- status_msg += f"- Verbatim column: {col_info['verbatim_column']}\n"
1242
-
1243
- # Add dynamic topic prefix info
1244
- if col_info.get('dynamic_topic_prefix'):
1245
- status_msg += f"- Dynamic topic prefix extracted: '{col_info['dynamic_topic_prefix']}'\n"
1246
-
1247
- # Extract unique topics, categories, and sentiments
1248
- num_topics, num_categories, num_sentiments = transformer.extract_unique_topics_and_categories()
1249
- status_msg += f"\n🎯 Found {num_topics} unique topics\n"
1250
- status_msg += f"🏷️ Found {num_categories} unique categories\n"
1251
- status_msg += f"💭 Found {num_sentiments} unique sentiments\n"
1252
-
1253
- # Transform data
1254
- shape = transformer.transform_data()
1255
- status_msg += f"\n✨ Transformed data shape: {shape[0]} rows × {shape[1]} columns\n"
1256
- status_msg += f"📊 Binary matrix created with T_, S_, C_ prefixes and Verbatim sentiment columns\n"
1257
- status_msg += f"🔧 T_ columns: 1 if topic present in ABSA column, 0 otherwise\n"
1258
- status_msg += f"🔧 S_ columns: contain actual sentiment values (not 1/0)\n"
1259
- status_msg += f"🔧 C_ columns: 1 if category assigned, 0 otherwise\n"
1260
- status_msg += f"🔧 Verbatim_Positive/Neutral/Negative: 1 if respective sentiment found in ABSA, 0 otherwise\n"
1261
-
1262
- # Analyze if requested
1263
- analysis_result = ""
1264
- if analyze_data:
1265
- analysis_result = transformer.analyze_data()
1266
-
1267
- # Save transformed data
1268
- output_file = transformer.save_transformed_data(output_format)
1269
- status_msg += f"\n💾 File saved successfully: {os.path.basename(output_file)}\n"
1270
- #status_msg += f"📥 File download should start automatically\n"
1271
-
1272
- return status_msg, analysis_result, output_file
1273
-
1274
- except Exception as e:
1275
- error_msg = f"❌ Error: {str(e)}\n\n{traceback.format_exc()}"
1276
- return error_msg, "", None
1277
-
1278
-
1279
- # Create Gradio interface
1280
- with gr.Blocks(title="Binary Matrix Feedback Transformer", css="""
1281
- .column-selector .form-check {
1282
- display: block !important;
1283
- margin-bottom: 8px !important;
1284
- }
1285
- .column-selector .form-check-input {
1286
- margin-right: 8px !important;
1287
- }
1288
- """) as demo:
1289
- gr.Markdown("""
1290
- # 📊 Binary Matrix Feedback Transformer
1291
- Transform feedback data with delimited topic and sentiment columns into binary matrix format.
1292
-
1293
- ### 🔧 Processing Logic:
1294
- - **Automatic Topic Prefix Detection**: Extracts topic prefix from columns containing "Category:" by finding text between "Category:" and "("
1295
- - **Verbatim_Positive/Neutral/Negative**: Set to 1 if respective sentiment is found in ABSA column, 0 otherwise
1296
- - **T_ Columns**: Set to 1 if topic is present in ABSA column, 0 otherwise
1297
- - **S_ Columns**: One column per topic (e.g., S_Allgemeine_Zufriedenheit) containing actual sentiment values
1298
- - **C_ Columns**: Set to 1 if category is assigned, 0 otherwise
1299
-
1300
- ### 📋 Data Format Requirements:
1301
- - **Topics**: Delimited by `|` (pipe) in columns identified by dynamic or manual prefix
1302
- - **Sentiments**: Format `Topic::Sentiment|Topic2::Sentiment2` in ABSA columns
1303
- - **Categories**: Delimited by `|` (pipe) in "Categories:" columns
1304
-
1305
- ### 🆕 Key Features:
1306
- - **Dynamic Topic Prefix Extraction**: Automatically extracts topic prefix from "Category:" columns
1307
- - **Verbatim_** columns detect overall sentiment presence regardless of topic
1308
- - **T_** columns based on ABSA column presence (topics that have sentiment data)
1309
- - **S_** columns contain actual sentiment values (not binary 1/0)
1310
- """)
1311
-
1312
- with gr.Row():
1313
- with gr.Column(scale=1):
1314
- # File upload
1315
- gr.Markdown("### 📋 1. Source file upload")
1316
- input_file = gr.File(
1317
- label="Upload Input File",
1318
- file_types=[".xlsx", ".xls", ".csv", ".txt"],
1319
- type="filepath"
1320
- )
1321
-
1322
- # Combined column selector
1323
- gr.Markdown("### 📋 2. Column Selection")
1324
- column_selector = gr.CheckboxGroup(
1325
- choices=[],
1326
- value=[],
1327
- label="Select Columns to Include",
1328
- info="Upload a file first to see available columns"
1329
- )
1330
-
1331
- with gr.Column(scale=1):
1332
- # Configuration parameters
1333
- gr.Markdown("### ⚙️ 3. Configuration")
1334
-
1335
- topic_prefix = gr.Textbox(
1336
- label="Topic Column Identifier (Fallback)",
1337
- value="Topic:",
1338
- info="Fallback identifier if dynamic extraction from Category: column fails"
1339
- )
1340
-
1341
- sentiment_prefix = gr.Textbox(
1342
- label="Sentiment Column Prefix (ABSA)",
1343
- value="ABSA:",
1344
- info="Prefix to identify sentiment columns (format: Topic::Sentiment)"
1345
- )
1346
-
1347
- category_prefix = gr.Textbox(
1348
- label="Category Column Prefix",
1349
- value="Categories:",
1350
- info="Prefix to identify category columns"
1351
- )
1352
-
1353
- text_column = gr.Textbox(
1354
- label="Text/Verbatim Column Pattern",
1355
- value="TEXT",
1356
- info="Pattern to identify verbatim text column (for reference only)"
1357
- )
1358
-
1359
- recommendation_column = gr.Textbox(
1360
- label="Recommendation Column Name",
1361
- value="Q4_Weiterempfehlung",
1362
- info="Column containing recommendation scores (for reference only)"
1363
- )
1364
-
1365
- output_format = gr.Radio(
1366
- label="Output Format",
1367
- choices=["xlsx", "csv"],
1368
- value="xlsx"
1369
- )
1370
-
1371
- analyze_checkbox = gr.Checkbox(
1372
- label="Analyze transformed data",
1373
- value=True
1374
- )
1375
-
1376
- # Transform button
1377
- transform_btn = gr.Button("🔄 4. Transform to Binary Matrix & Download", variant="primary", size="lg")
1378
-
1379
- # Output sections
1380
- with gr.Row():
1381
- with gr.Column():
1382
- status_output = gr.Textbox(
1383
- label="Processing Status",
1384
- lines=12,
1385
- interactive=False
1386
- )
1387
-
1388
- with gr.Column():
1389
- analysis_output = gr.Markdown(
1390
- label="Data Analysis"
1391
- )
1392
-
1393
- # Download section
1394
- with gr.Row():
1395
- with gr.Column():
1396
- gr.Markdown("### 📥 Download Status")
1397
- gr.Markdown("Please click on the link inside the output file size value to download the transformed file (the number value on the right hand side below). You may need to right click and select Save Link As (or something similar)")
1398
- output_file = gr.File(
1399
- label="Transformed Binary Matrix (Auto-Download)",
1400
- interactive=False,
1401
- visible=True
1402
- )
1403
-
1404
- # Event handlers
1405
- input_file.change(
1406
- fn=get_column_selector,
1407
- inputs=[input_file],
1408
- outputs=[column_selector]
1409
- )
1410
-
1411
- transform_btn.click(
1412
- fn=process_file,
1413
- inputs=[
1414
- input_file,
1415
- topic_prefix,
1416
- sentiment_prefix,
1417
- category_prefix,
1418
- text_column,
1419
- recommendation_column,
1420
- output_format,
1421
- analyze_checkbox,
1422
- column_selector
1423
- ],
1424
- outputs=[status_output, analysis_output, output_file]
1425
- )
1426
-
1427
- # Examples section
1428
- gr.Markdown("""
1429
- ### 📝 Example Transformations:
1430
-
1431
- **Input Data with Dynamic Topic Extraction:**
1432
- ```
1433
- | Column: "Category: Service (ABC)" | ABSA: Sentiments | Categories: Issues |
1434
- | 1 | Service::Negative|Quality::Positive | Issues|Support |
1435
- ```
1436
-
1437
- **System will:**
1438
- 1. Extract "Service:" from "Category: Service (ABC)" column
1439
- 2. Use "Service:" to identify topic columns instead of "Topic:"
1440
-
1441
- **Output Binary Matrix:**
1442
- ```
1443
- | feedback_id | Verbatim_Positive | Verbatim_Neutral | Verbatim_Negative | T_Service | T_Quality | S_Service | S_Quality | C_Issues | C_Support |
1444
- | 1 | 1 | 0 | 1 | 1 | 1 | Negative | Positive | 1 | 1 |
1445
- ```
1446
-
1447
- ### 💡 Dynamic Topic Prefix Logic:
1448
- - Searches for columns containing "Category:"
1449
- - Extracts text between "Category:" and "(" (e.g., "Service" from "Category: Service (ABC)")
1450
- - Adds ":" to create the topic prefix (e.g., "Service:")
1451
- - Uses this prefix to identify topic columns
1452
- - Falls back to manual "Topic Column Identifier" if extraction fails
1453
-
1454
- ### 🔍 Key Changes in This Version:
1455
- - **NEW**: Automatic extraction of topic prefix from Category columns
1456
- - Dynamically identifies topic columns based on extracted prefix
1457
- - Maintains all other functionality (Verbatim columns, T_, S_, C_ logic)
1458
- - Provides fallback to manual topic prefix if extraction fails
1459
- """)
1460
-
1461
- # Launch the app
1462
- if __name__ == "__main__":
1463
- demo.launch()
1464
-
 
700
 
701
  # Launch the app
702
  if __name__ == "__main__":
703
+ demo.launch()