ncardian commited on
Commit
881b7d4
ยท
verified ยท
1 Parent(s): 619eecd

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -51
app.py CHANGED
@@ -9,6 +9,7 @@ from datetime import datetime
9
  from langchain.llms.base import LLM
10
  import csv
11
  import re
 
12
  import pandas as pd
13
  from io import StringIO
14
  from typing import Optional, List
@@ -238,27 +239,46 @@ def analyze_code_execution(code: str, execution_result: dict, df: pd.DataFrame)
238
  3. Error (jika ada):
239
  {error if error else 'Tidak ada error'}
240
 
241
- analisis juga data berikut:
242
- - Success: {execution_result['success']}
243
- - Output: {execution_result.get('stdout', 'No output')}
244
- - Figure: {execution_result.get('figure', 'None')}
245
- - Error: {execution_result.get('error', 'None')}
246
- - Variables created: {list(execution_result.get('variables', {}).keys())}
247
- - {code}
248
 
249
- Dataframe shape: {df.shape}
 
 
 
250
 
251
- Berikan insight lebih lanjut berdasarkan seluruh kolom data yang ada pada DataFrame. Fokus pada:
252
- - Fokuslah untuk membahas hasil eksekusi
253
- - Jangan menganalisis dari data yg tidak ada
254
- - Temuan atau pola menarik yang muncul dari data
255
- - Hubungan atau korelasi antara kolom-kolom dalam data
256
- - Faktor yang dapat mempengaruhi hasil analisis lebih lanjut
257
- - Saran untuk pengolahan atau analisis lebih lanjut yang dapat dilakukan pada data ini
258
- - Jangan membahas kode Python-nya
259
- - Berikan insight secara singkat dan padat algoritma yang perlu digunakan seperti pada data science dan AI beserta kegunaannya terhadap analisis
260
- - Gunakan bahasa Indonesia yang mudah dipahami
261
- - Hanya gunakan kata ganti orang ketiga
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
  """
263
 
264
  # Get analysis from the text model
@@ -542,7 +562,7 @@ with col1a:
542
 
543
  with col2a: # Sidebar untuk chatbot
544
  with st.container(height=570):
545
- st.title("๐Ÿ“Š Data Analysis Powered by AI Assistance")
546
  st.markdown("Analyze your CSV data with LLM Models")
547
 
548
  def reset_data_state():
@@ -680,7 +700,7 @@ with col2a: # Sidebar untuk chatbot
680
  with st.spinner("Generating merge preview..."):
681
  try:
682
  if merge_option == "single data":
683
- preview_df = dataframes
684
  elif merge_option == "Horizontal (concat columns)":
685
  # Find common indices across ALL dataframes
686
  common_indices = dataframes[0].index
@@ -1071,8 +1091,7 @@ with col2a: # Sidebar untuk chatbot
1071
  STRICT RULES (NUMBERED PRIORITY):
1072
  1. CODE STRUCTURE:
1073
  - Return complete executable code in ```python block
1074
- - All new variables MUST be added as new columns to existing 'df' using df['new_column'] syntax
1075
- - Never add a new variable (such as a list, Series, or array) to df if its length is less than the number of rows in df.
1076
  - Never create new DataFrames or use merge/join operations
1077
  - Print calculation result (such as a list, Series, or array) in console
1078
  - Define all temporary variables explicitly
@@ -1081,14 +1100,17 @@ with col2a: # Sidebar untuk chatbot
1081
  - Use only columns from: {list(df_columns)}
1082
  - For new data storage:
1083
  if isinstance(result, (pd.Series, list, np.ndarray)):
1084
- df[new_col_name] = result
1085
- elif numerical/string value:
1086
- df[new_col_name] = [value]*len(df)
1087
- - For column matching:
1088
- from fuzzywuzzy import process
1089
- def find_best_match(query, cols, threshold=70):
1090
- # [existing fuzzy match implementation]
1091
-
 
 
 
1092
  3. COLUMN CREATION RULES:
1093
  a. Untuk hasil operasi matematika:
1094
  df['hasil_kalkulasi'] = df['col1'] + df['col2']
@@ -1099,33 +1121,48 @@ with col2a: # Sidebar untuk chatbot
1099
  c. Untuk agregasi grup:
1100
  df['rata_grup'] = df.groupby('kolom_grup')['target'].transform('mean')
1101
 
1102
- d. Untuk hasil statistik:
1103
- df['zscore'] = (df['nilai'] - df['nilai'].mean())/df['nilai'].std()
1104
-
1105
- 4. VISUALIZATION:
1106
- - Visualisasi harus menggunakan kolom dari df yang telah dimodifikasi
1107
- - Contoh: plt.plot(df['kolom_baru'], df['kolom_lama'])
1108
-
1109
- 5. OUTPUT HANDLING:
1110
- - Untuk menampilkan kolom baru:
1111
- print(f"Kolom baru yang dibuat:", list(df.columns[-N:])) # N = jumlah kolom baru
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1112
  print(df[['kolom_baru_1', 'kolom_baru_2']].head())
1113
-
1114
- 6. ERROR PREVENTION:
1115
- - Cek panjang data sebelum membuat kolom baru:
1116
- if len(variable) != len(df):
1117
- raise ValueError("Panjang variabel tidak sesuai dengan DataFrame")
1118
- - Gunakan nama kolom unik:
1119
  if 'nama_kolom' in df.columns:
1120
  df['nama_kolom_rev'] = ... # tambahkan suffix jika sudah ada
 
 
 
 
 
1121
 
1122
  FINAL CHECK:
1123
  1. Pastikan tidak ada operasi merge/join/concat
1124
- 2. Verifikasi semua hasil kalkulasi ada di df sebagai kolom
1125
- 3. Cek konsistensi indeks untuk kolom baru
1126
- 4. Pastikan print terakhir menampilkan df dengan kolom baru
1127
  5. Jangan menampilkan penjelasan apapun dari kode
1128
- 6. Jika user menyebut 'pivot' gunakan fungsi groupby
1129
  """
1130
 
1131
  # Mode handling
 
9
  from langchain.llms.base import LLM
10
  import csv
11
  import re
12
+ import ast
13
  import pandas as pd
14
  from io import StringIO
15
  from typing import Optional, List
 
239
  3. Error (jika ada):
240
  {error if error else 'Tidak ada error'}
241
 
242
+ Format analisis yang diharapkan:
243
+ A. Visualisasi Grafik:
244
+ - Jelaskan jenis visualisasi yang dihasilkan
245
+ - Identifikasi pola atau tren utama yang terlihat
246
+ - Berikan interpretasi bisnis dari visual tersebut
 
 
247
 
248
+ B. Output Konsol:
249
+ - Terjemahkan nilai numerik/metrik ke dalam konteks bisnis
250
+ - Jelaskan signifikansi statistik dari nilai yang ditampilkan
251
+ - Highlight angka-angka kunci yang penting untuk pengambilan keputusan
252
 
253
+ C. Variabel Baru:
254
+ - Untuk kolom baru di DataFrame: jelaskan hubungannya dengan kolom lain
255
+ - Untuk variabel statistik: jelaskan implikasi analitisnya
256
+ - Klasifikasikan tipe variabel (numerik/kategorikal/deret waktu)
257
+
258
+ D. Rekomendasi Lanjutan:
259
+ - Sarankan teknik analisis tambahan yang relevan (Contoh: "Untuk memahami hubungan non-linear, bisa digunakan regresi polinomial")
260
+ - Rekomendasikan jenis visualisasi pendukung lainnya
261
+ - Identifikasi potensi masalah data yang perlu diperhatikan
262
+
263
+ Aturan ketat:
264
+ 1. JANGAN menyebutkan detail teknis kode atau library
265
+ 2. Fokus pada interpretasi bisnis/bisnis
266
+ 3. Gunakan analogi sehari-hari untuk konsep statistik kompleks
267
+ 4. Prioritaskan insight yang actionable
268
+ 5. Batasi analisis maksimal 3 poin utama per kategori
269
+ 6. Gunakan format poin-poin dengan penomoran jelas
270
+
271
+ Contoh struktur jawaban:
272
+ 'Analisis menunjukkan:
273
+ 1. Pada visualisasi terlihat... [interpretasi grafik]
274
+ 2. Nilai R-squared sebesar 0.85 menunjukkan... [penjelasan metrik]
275
+ 3. Kolom baru "prediksi" memiliki... [analisis variabel]
276
+ Rekomendasi: [saran spesifik]'
277
+
278
+ Data pendukung:
279
+ - Dimensi DataFrame: {df.shape} baris x {len(df.columns)} kolom
280
+ - Kolom tersedia: {list(df.columns)}
281
+ - Statistik deskriptif terakhir: {df.describe().to_string() if not df.empty else 'Tidak tersedia'}
282
  """
283
 
284
  # Get analysis from the text model
 
562
 
563
  with col2a: # Sidebar untuk chatbot
564
  with st.container(height=570):
565
+ st.title("๐Ÿ“Š Chatbot Data Analysis Coder")
566
  st.markdown("Analyze your CSV data with LLM Models")
567
 
568
  def reset_data_state():
 
700
  with st.spinner("Generating merge preview..."):
701
  try:
702
  if merge_option == "single data":
703
+ preview_df = dataframes[0]
704
  elif merge_option == "Horizontal (concat columns)":
705
  # Find common indices across ALL dataframes
706
  common_indices = dataframes[0].index
 
1091
  STRICT RULES (NUMBERED PRIORITY):
1092
  1. CODE STRUCTURE:
1093
  - Return complete executable code in ```python block
1094
+ - All new variables with len(var) same lenght with len(df.shape[0]) MUST be added as new columns to existing 'df' using df['new_column'] syntax
 
1095
  - Never create new DataFrames or use merge/join operations
1096
  - Print calculation result (such as a list, Series, or array) in console
1097
  - Define all temporary variables explicitly
 
1100
  - Use only columns from: {list(df_columns)}
1101
  - For new data storage:
1102
  if isinstance(result, (pd.Series, list, np.ndarray)):
1103
+ if len(result) == len(df): # Check length match
1104
+ df[new_col_name] = result
1105
+ else:
1106
+ print("\\nHasil kalkulasi (ukuran {{}}):".format(len(result)))
1107
+ print(result)
1108
+ elif isinstance(result, (int, float, str, dict, pd.DataFrame, np.ndarray)):
1109
+ print("\\nHasil skalar/metrik:")
1110
+ print(result)
1111
+ else:
1112
+ print("\\nHasil tidak tersimpan:", type(result))
1113
+
1114
  3. COLUMN CREATION RULES:
1115
  a. Untuk hasil operasi matematika:
1116
  df['hasil_kalkulasi'] = df['col1'] + df['col2']
 
1121
  c. Untuk agregasi grup:
1122
  df['rata_grup'] = df.groupby('kolom_grup')['target'].transform('mean')
1123
 
1124
+ d. Contoh khusus untuk statistik:
1125
+ # Untuk metrik seperti R2/korelasi
1126
+ corr_matrix = df.corr()
1127
+ print("\\nMatriks korelasi:")
1128
+ print(corr_matrix)
1129
+
1130
+ # Untuk nilai skalar
1131
+ r2_score = calculate_r2()
1132
+ print("\\nR-squared:", r2_score)
1133
+ e. contoh untuk hasil prediksi
1134
+ df['Predict data'] = model.predict(X)
1135
+
1136
+ 4. OUTPUT HANDLING:
1137
+ - Untuk hasil non-kolom (skalar/matriks/agregat):
1138
+ print("\\nHasil analisis:")
1139
+ print(result)
1140
+
1141
+ - Untuk visualisasi:
1142
+ plt.figure()
1143
+ plt.plot(...)
1144
+ plt.show()
1145
+
1146
+ - Untuk kolom baru:
1147
+ print("\\n5 baris pertama kolom baru:")
1148
  print(df[['kolom_baru_1', 'kolom_baru_2']].head())
1149
+
1150
+ 5. ERROR PREVENTION:
1151
+ - Cek konflik nama kolom:
 
 
 
1152
  if 'nama_kolom' in df.columns:
1153
  df['nama_kolom_rev'] = ... # tambahkan suffix jika sudah ada
1154
+
1155
+ - Untuk operasi yang menghasilkan array ukuran berbeda:
1156
+ # Langsung print jangan simpan ke df
1157
+ conf_matrix = confusion_matrix(...)
1158
+ print("Confusion Matrix:", conf_matrix)
1159
 
1160
  FINAL CHECK:
1161
  1. Pastikan tidak ada operasi merge/join/concat
1162
+ 2. Hasil dengan ukuran != len(df) harus langsung di-print
1163
+ 3. Skalar dan matriks tidak boleh disimpan sebagai kolom
1164
+ 4. Print statement harus menunjukkan tipe hasil yang jelas
1165
  5. Jangan menampilkan penjelasan apapun dari kode
 
1166
  """
1167
 
1168
  # Mode handling