mtyrrell commited on
Commit
b0ab312
·
1 Parent(s): 653a8de

eval pipeline

Browse files
.DS_Store CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
 
app.py CHANGED
@@ -107,6 +107,6 @@ if st.button("Analyze Document"):
107
  if 'key0' in st.session_state:
108
 
109
  vulnerability_analysis.vulnerability_display()
110
- target_analysis.target_display(model_sel_name=model_sel_name)
111
 
112
 
 
107
  if 'key0' in st.session_state:
108
 
109
  vulnerability_analysis.vulnerability_display()
110
+ target_analysis.target_display(model_sel_name=model_sel_name, doc_name = doc_name)
111
 
112
 
appStore/__pycache__/__init__.cpython-310.pyc CHANGED
Binary files a/appStore/__pycache__/__init__.cpython-310.pyc and b/appStore/__pycache__/__init__.cpython-310.pyc differ
 
appStore/__pycache__/vulnerability_analysis.cpython-310.pyc CHANGED
Binary files a/appStore/__pycache__/vulnerability_analysis.cpython-310.pyc and b/appStore/__pycache__/vulnerability_analysis.cpython-310.pyc differ
 
appStore/rag.py CHANGED
@@ -11,15 +11,22 @@ from huggingface_hub import InferenceClient
11
  # Get openai API key
12
  hf_token = os.environ["HF_API_KEY"]
13
 
 
14
  # define a special function for putting the prompt together (as we can't use haystack)
15
  def get_prompt(context, label):
16
- base_prompt="Summarize the following context efficiently in bullet points, the less the better - but keep concrete goals. \
 
17
  Summarize only elements of the context that address vulnerability of "+label+" to climate change. \
18
  If there is no mention of "+label+" in the context, return: 'No clear references to vulnerability of "+label+" found'. \
 
 
 
19
  Do not include an introduction sentence, just the bullet points as per below. \
20
  Formatting example: \
21
- - Bullet point 1 \
22
- - Bullet point 2 \
 
 
23
  "
24
 
25
  prompt = base_prompt+"; Context: "+context+"; Answer:"
 
11
  # Get openai API key
12
  hf_token = os.environ["HF_API_KEY"]
13
 
14
+
15
  # define a special function for putting the prompt together (as we can't use haystack)
16
  def get_prompt(context, label):
17
+ base_prompt="Summarize the following context efficiently in English-language bullet points, the less the better - \
18
+ but ensure that any concrete goals expressed in the context are kept clearly articulated in the response. \
19
  Summarize only elements of the context that address vulnerability of "+label+" to climate change. \
20
  If there is no mention of "+label+" in the context, return: 'No clear references to vulnerability of "+label+" found'. \
21
+ If there is only minimal mention of "+label+" in the context, return only the summarizations (no additional commentary)'. \
22
+ VERY IMPORTANT: Always provide the summarization in English. \
23
+ If the source language is not English, translate the response to English. \
24
  Do not include an introduction sentence, just the bullet points as per below. \
25
  Formatting example: \
26
+ * Bullet point 1 \
27
+ * Bullet point 2 \
28
+ * Bullet point 3 \
29
+ RESPOND IN ENGLISH ONLY! \
30
  "
31
 
32
  prompt = base_prompt+"; Context: "+context+"; Answer:"
appStore/target.py CHANGED
@@ -18,6 +18,16 @@ import xlsxwriter
18
  import plotly.express as px
19
  from utils.target_classifier import label_dict
20
  from appStore.rag import run_query
 
 
 
 
 
 
 
 
 
 
21
 
22
  # Declare all the necessary variables
23
  classifier_identifier = 'target'
@@ -81,7 +91,272 @@ def app():
81
  st.session_state.key2 = df
82
 
83
 
84
- def target_display(model_sel_name):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  ### TABLE Output ###
87
 
@@ -102,22 +377,146 @@ def target_display(model_sel_name):
102
  # st.write(df_agg)
103
 
104
  st.markdown("----")
105
- st.markdown('**DOCUMENT FINDINGS SUMMARY BY VULNERABILITY LABEL:**')
106
-
107
- # construct RAG query for each label, send to openai and process response
108
- for i in range(0,len(df_agg)):
109
- st.write(df_agg['Vulnerability Label'].iloc[i])
110
- run_query(context = df_agg['text'].iloc[i], label = df_agg['Vulnerability Label'].iloc[i], model_sel_name=model_sel_name)
111
-
112
-
113
-
114
-
115
-
116
-
117
-
118
-
119
-
120
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
 
123
 
 
18
  import plotly.express as px
19
  from utils.target_classifier import label_dict
20
  from appStore.rag import run_query
21
+ from math import exp
22
+ import re
23
+ import json
24
+
25
+ import nltk
26
+ from nltk.corpus import stopwords
27
+ nltk.download('stopwords')
28
+
29
+ import openai
30
+ openai_api_key = os.environ["OPEN_AI_KEY"]
31
 
32
  # Declare all the necessary variables
33
  classifier_identifier = 'target'
 
91
  st.session_state.key2 = df
92
 
93
 
94
+
95
+ vc_prompt="""
96
+ You are assessing the accuracy of a multi-label classifier. The classifier seeks to assess the relevance of a given passage of context to any of 18 classes:
97
+
98
+ 'Agricultural communities',
99
+ 'Children',
100
+ 'Coastal communities',
101
+ 'Ethnic, racial or other minorities',
102
+ 'Fishery communities',
103
+ 'Informal sector workers',
104
+ 'Members of indigenous and local communities',
105
+ 'Migrants and displaced persons',
106
+ 'Older persons',
107
+ 'Other',
108
+ 'Persons living in poverty',
109
+ 'Persons with disabilities',
110
+ 'Persons with pre-existing health conditions',
111
+ 'Residents of drought-prone regions',
112
+ 'Rural populations',
113
+ 'Sexual minorities (LGBTQI+)',
114
+ 'Urban populations',
115
+ 'Women and other genders'
116
+
117
+ If there is a semantic relevance or keyword(s) match between labels and context, then assess accuracy as a boolean True.
118
+ Assessing class relevance may be tricky in some cases as the context can use technical language which is sometimes ambiguous. Please take your time to ensure a robust assessment.
119
+ If you can't decide, err on the side of the classifier, and assume it is correct.
120
+
121
+ Use the examples below for reference:
122
+
123
+ EXAMPLE 1
124
+
125
+ LABEL: ['Agricultural communities', 'Residents of drought-prone regions']
126
+
127
+ CONTEXT: "Future climatic predictions for Kenya indicate possible temperature increase of 1C by 2020 and 2.3C by 2050. These changes unless effectively mitigated, will likely result to erosion of the productive assets and the weakening of coping strategies and resilience of rain-fed farming systems, especially in the arid and semi-arid lands."
128
+
129
+ RESPONSE: True
130
+
131
+ EXAMPLE 2
132
+
133
+ LABEL: ['Fishery communities']
134
+
135
+ CONTEXT: "The reduced water availability resulting from frequent droughts also limits aquaculture development. Forests and agroforestry The farmed fisheries resources include the trout fish in cold water high altitude areas and tilapia, catfish, common carp for warmer water low altitude areas. Figure 5 shows the quantities and monetary value of fish produced in Kenya between 2005 and 2016."
136
+
137
+ RESPONSE: True
138
+
139
+ EXAMPLE 3
140
+
141
+ LABEL: ['Persons with disabilities']
142
+
143
+ CONTEXT: "In addressing climate change issues, public entities are required to undertake public awareness and consultations, and ensure gender mainstreaming, in line with the Constitution and the Climate Change Bill (2014). 5. Means of implementation Kenya's contribution will be implemented with both domestic and international support."
144
+
145
+ RESPONSE: False
146
+
147
+ EXAMPLE 4
148
+
149
+ LABEL: ['Children', 'Women and other genders']
150
+
151
+ CONTEXT: "Enhance quality control and food safety by relevant institutions along crop, livestock and fisheries value chains. Enhance use of low greenhouse gas emitting fish production technologies and practices. Promote integrated farming systems comprising crops, livestock, aquaculture and farm forestry. Create awareness and capacity build women, youth and venerable groups (WY&VG) on CSA."
152
+
153
+ RESPONSE: True
154
+
155
+ EXAMPLE 5
156
+
157
+ LABEL: ['Ethnic, racial or other minorities']
158
+
159
+ CONTEXT: "Harmonize livestock vaccinations across the bordering counties and across the international borders. Facilitate management of veterinary drug residues, carcasses and agrochemicals. Promote efficient use of farm mechanization. Promote mechanized and animal powered conservation tillage practices as compared to conventional tillage. Promote value addition of farm produce through cottage industries."
160
+
161
+ RESPONSE: False
162
+
163
+ EXAMPLE 6
164
+
165
+ LABEL: ['Agricultural communities']
166
+
167
+ CONTEXT: "There is also no traceability mechanism for produce and products from farm to folk. Value addition will ensure longer shelf life, reduced transaction costs and higher incomes. Summary of Actions: Identify and promote existing value addition technologies. Incentivize the private sector to invest in agricultural value addition."
168
+
169
+ RESPONSE: False
170
+
171
+ EXAMPLE 7
172
+
173
+ LABEL: ['Agricultural communities', 'Rural populations']
174
+
175
+ CONTEXT: "Kenya's total greenhouse gas (GHG) emissions are relatively low, standing at 73 MtCO2eq in 2010, out of which 75%/ are from the land use, land-use change and forestry (LULUCF) and agriculture sectors. This may be explained by the reliance on wood fuel by a large proportion of the population coupled with the increasing demand for agricultural land and urban development."
176
+
177
+ RESPONSE: True
178
+
179
+ Return the assessment as a boolean True or False.
180
+ Return only the boolean, and nothing else.
181
+
182
+ Now assess the following sample:
183
+
184
+
185
+ """
186
+
187
+ tma_prompt="""
188
+ You are assessing the accuracy of a binary ('YES'/'NO') classifier. The classifier classifies a given passage of text as to whether it contains reference to a target, measure, action, and plans
189
+ in the context of the United Nations Framework Convention on Climate Change (UNFCCC) and the Paris Agreement.
190
+ The text is extracted from Nationally Determined Contributions (NDCs) documents.
191
+ The concepts of targets, measures, actions, and plans are defined below:
192
+
193
+ 1. Targets
194
+
195
+ • Definition: Targets in the NDCs refer to the specific, quantified objectives that each country sets for itself to reduce greenhouse gas (GHG) emissions and mitigate climate change. These targets reflect the level of ambition a country is willing to commit to in its climate action.
196
+ • Example in NDCs: A common form of a target is a percentage reduction in GHG emissions by a certain year, such as “reducing emissions by 50% by 2030 compared to 1990 levels.” Targets can also be sector-specific, such as setting renewable energy capacity goals.
197
+
198
+ 2. Measures
199
+
200
+ • Definition: Measures are the policies, regulations, and actions that are implemented to achieve the targets set in the NDCs. These are the instruments through which a country can ensure that it is on the right path to meet its climate goals.
201
+ • Example in NDCs: Measures can include implementing a carbon tax, introducing renewable energy incentives, or regulations to improve energy efficiency in buildings or transportation sectors. These could also involve reforestation or land-use changes to enhance carbon sinks.
202
+
203
+ 3. Actions
204
+
205
+ • Definition: Actions refer to the specific activities, projects, or steps that are undertaken to implement the measures and meet the set targets. Actions are the tangible efforts that contribute to reducing emissions or adapting to climate change impacts.
206
+ • Example in NDCs: Actions might include building solar or wind power plants, electrifying transportation systems, or retrofitting existing infrastructure to make it more energy efficient. Actions are often the ground-level, operational steps that translate plans into reality.
207
+
208
+
209
+ If you agree with the classifier, then assess accuracy as a boolean True.
210
+ Note - assessing targets, measures and actions may be tricky in some cases as the text can use technical language which is sometimes ambiguous.
211
+ Please take your time to ensure a robust assessment.
212
+ If you can't decide, err on the side of the classifier, and assume it is correct.
213
+
214
+ EXAMPLE 1:
215
+
216
+ LABEL: 'YES'
217
+
218
+ CONTEXT: "This will lead to more climate related vulnerabilities thereby predisposing farming communities to food insecurity and more poverty. In response to this scenario, the Government has been exploring innovative and transformative measures to assist stakeholders across the agricultural value chains to manage the effects of current and projected change of climate patterns."
219
+
220
+ RESPONSE: True
221
+
222
+ EXAMPLE 2:
223
+
224
+ LABEL: 'NO'
225
+
226
+ CONTEXT: "Kenya's total greenhouse gas (GHG) emissions are relatively low, standing at 73 MtCO2eq in 2010, out of which 75%/ are from the land use, land-use change and forestry (LULUCF) and agriculture sectors. This may be explained by the reliance on wood fuel by a large proportion of the population coupled with the increasing demand for agricultural land and urban development."
227
+
228
+ RESPONSE: True
229
+
230
+ EXAMPLE 3:
231
+
232
+ LABEL: 'YES'
233
+
234
+ CONTEXT: "1.1 National Circumstances Kenya is located in the Greater Horn of Africa region, which is highly vulnerable to the impacts of climate change. More than 80% of the country’s landmass is arid and semi-arid land (ASAL) with poor infrastructure, and other developmental challenges."
235
+
236
+ RESPONSE: True
237
+
238
+ Return the assessment as a boolean True or False.
239
+ Return only the boolean, and nothing else.
240
+
241
+ Now assess the following sample:
242
+
243
+ """
244
+
245
+
246
+
247
+ def send_to_chatgpt_api(context, label, prompt, openai_api_key, logprobs_flag=None, logprobs_n=None):
248
+
249
+ # Combine the result object and context with the new prompt
250
+ combined_message = f"""
251
+ {prompt}
252
+ LABEL: {label}
253
+ CONTEXT: {context}
254
+ RESPONSE:
255
+ """
256
+
257
+ # Set up the OpenAI API
258
+ openai.api_key = openai_api_key
259
+
260
+
261
+ # Send the combined message to the ChatGPT API
262
+ response = openai.ChatCompletion.create(
263
+ # model="gpt-4o-mini",
264
+ model="gpt-4o-mini-2024-07-18",
265
+ # model="gpt-4o-2024-08-06",
266
+ messages=[
267
+ {"role": "system", "content": "You are ChatGPT."},
268
+ {"role": "user", "content": combined_message}
269
+ ],
270
+ logprobs=logprobs_flag, # whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the content of message..
271
+ top_logprobs=logprobs_n,
272
+ )
273
+
274
+ # Get the response from the API
275
+ if logprobs_flag:
276
+ gpt_response = response.choices[0].logprobs.content[0].top_logprobs[0]
277
+
278
+ else:
279
+ gpt_response = response.choices[0].message['content']
280
+
281
+ return gpt_response
282
+
283
+
284
+ # Fuzzy matching
285
+ def levenshtein_distance(a, b):
286
+ # Initialize the matrix
287
+ dp = [[0 for _ in range(len(b) + 1)] for _ in range(len(a) + 1)]
288
+
289
+ # Base cases
290
+ for i in range(len(a) + 1):
291
+ dp[i][0] = i
292
+ for j in range(len(b) + 1):
293
+ dp[0][j] = j
294
+
295
+ # Fill the matrix
296
+ for i in range(1, len(a) + 1):
297
+ for j in range(1, len(b) + 1):
298
+ if a[i - 1] == b[j - 1]:
299
+ cost = 0
300
+ else:
301
+ cost = 1
302
+ dp[i][j] = min(dp[i - 1][j] + 1, # Deletion
303
+ dp[i][j - 1] + 1, # Insertion
304
+ dp[i - 1][j - 1] + cost) # Substitution
305
+
306
+ # Return the Levenshtein distance
307
+ return dp[-1][-1]
308
+
309
+ def similarity_score(a, b):
310
+ max_len = max(len(a), len(b))
311
+ if max_len == 0:
312
+ return 1.0
313
+ return (max_len - levenshtein_distance(a, b)) / max_len
314
+
315
+ def remove_stopwords(text):
316
+ stop_words = set(stopwords.words('english'))
317
+ # Tokenize the string and filter out stopwords
318
+ return ' '.join([word for word in text.split() if word.lower() not in stop_words])
319
+
320
+ def fuzzy_match_sequence(sequence, long_string, threshold=0.4):
321
+ # If the sequence is a single string, split it into phrases (based on commas or similar punctuation)
322
+ if isinstance(sequence, str):
323
+ sequence = re.split(r',\s*|\s+', sequence)
324
+
325
+ # Remove stopwords from both the sequence and the long string
326
+ sequence = [remove_stopwords(phrase) for phrase in sequence]
327
+ long_string = remove_stopwords(long_string)
328
+
329
+ # Ensure that the input is now a list or tuple
330
+ if not isinstance(sequence, (list, tuple)):
331
+ sequence = list(sequence)
332
+
333
+ # Split the long string into words
334
+ long_string_words = long_string.split()
335
+
336
+ # Perform Levenshtein-based fuzzy matching and calculate overall similarity score
337
+ total_score = 0
338
+ matches = []
339
+ count_high_prob_matches = 0
340
+
341
+ for word in sequence:
342
+ # Find the best match for the current word in the long string
343
+ best_match_score, best_match_word = max((similarity_score(word, ls_word), ls_word) for ls_word in long_string_words)
344
+
345
+ # Only count matches with a similarity score above the threshold
346
+ if best_match_score >= threshold:
347
+ count_high_prob_matches += 1
348
+ # Cap the total score at 1 and calculate contribution
349
+ total_score += min(best_match_score, 1 - total_score) # Ensure the score doesn't go above 1
350
+
351
+ matches.append(f"Keyword '{word}' matched '{best_match_word}' with a similarity score of {best_match_score:.2f}")
352
+
353
+ # The total score should never exceed 1, ensure it is capped at 1
354
+ total_score = round(min(total_score, 1),2)
355
+
356
+ return total_score
357
+
358
+
359
+ def target_display(model_sel_name, doc_name):
360
 
361
  ### TABLE Output ###
362
 
 
377
  # st.write(df_agg)
378
 
379
  st.markdown("----")
380
+ st.markdown('**SUMMARY OF GOALS BY VULNERABILITY LABEL:**')
381
+
382
+ # Check if the results are already in session state
383
+ if 'results_df' not in st.session_state:
384
+ # Initialize an empty list to store the results
385
+ summary_list = []
386
+ results_list = []
387
+
388
+ # Process the data in the loop
389
+ for i in range(0, len(df_agg)):
390
+ st.write(df_agg['Vulnerability Label'].iloc[i])
391
+
392
+ # Run query to get the result
393
+ result = run_query(
394
+ context=df_agg['text'].iloc[i],
395
+ label=df_agg['Vulnerability Label'].iloc[i],
396
+ model_sel_name=model_sel_name
397
+ )
398
+
399
+ # Store the Vulnerability Label and the response in a list of dictionaries
400
+ summary_list.append({
401
+ 'document': doc_name,
402
+ 'text': df_agg['text'].iloc[i],
403
+ 'label': df_agg['Vulnerability Label'].iloc[i],
404
+ 'summary': result.get_full_content()
405
+ })
406
+
407
+
408
+ # Process the data in the loop
409
+ for i in range(0, len(df)):
410
+
411
+ # Send the result to the ChatGPT API and get the labeled response
412
+ vc_response = send_to_chatgpt_api(
413
+ context = df['text'].iloc[i],
414
+ label = df['Vulnerability Label'].iloc[i],
415
+ prompt = vc_prompt,
416
+ openai_api_key=openai_api_key,
417
+ logprobs_flag=True,
418
+ logprobs_n=1)
419
+
420
+ tma_response = send_to_chatgpt_api(
421
+ context = df['text'].iloc[i],
422
+ label = df['Specific action/target/measure mentioned'].iloc[i],
423
+ prompt = tma_prompt,
424
+ openai_api_key=openai_api_key,
425
+ logprobs_flag=True,
426
+ logprobs_n=1)
427
+
428
+
429
+ # Convert logprobs to % scale
430
+ vc_prob = np.round(np.exp(vc_response.logprob),2)
431
+ vc_token = vc_response.token
432
+
433
+ # Convert contrary predictions to probability of positive prediction (inverse)
434
+ if vc_token == 'False':
435
+ vc_prob_cnv = round(1 - vc_prob,2)
436
+ else:
437
+ vc_prob_cnv = vc_prob
438
+
439
+ # Do some fuzzy matching to check for class-related keywords in the text
440
+ vc_keywords = fuzzy_match_sequence(str(df['Vulnerability Label'].iloc[i]), str(df['text'].iloc[i]))
441
+
442
+ # Compute vulnerability classifciation eval
443
+ vc_eval = False
444
+ if vc_prob_cnv > 0.5 or vc_keywords > 0:
445
+ vc_eval = True
446
+
447
+ # Convert logprobs to % scale
448
+ tma_prob = np.round(np.exp(tma_response.logprob),2)
449
+ tma_token = tma_response.token
450
+
451
+ # Convert contrary predictions to probability of positive prediction (inverse)
452
+ if tma_token == 'False':
453
+ tma_prob_cnv = round(1 - tma_prob,2)
454
+ else:
455
+ tma_prob_cnv = tma_prob
456
+
457
+ # Compute TMA classification eval
458
+ tma_eval = False
459
+ if tma_prob_cnv > 0.5:
460
+ tma_eval = True
461
+
462
+ # Store the Vulnerability Label and the response in a list of dictionaries
463
+ results_list.append({
464
+ 'document': doc_name,
465
+ 'text': df['text'].iloc[i],
466
+ 'page': df['page'].iloc[i],
467
+ 'label': df['Vulnerability Label'].iloc[i],
468
+ 'target': df['Specific action/target/measure mentioned'].iloc[i],
469
+ 'VC_prob': vc_prob_cnv,
470
+ 'VC_keywords': vc_keywords,
471
+ 'VC_eval': vc_eval,
472
+ 'TMA_prob': tma_prob_cnv,
473
+ 'TMA_eval': tma_eval,
474
+ 'VC_check': None,
475
+ 'TMA_check': None,
476
+ })
477
+
478
+ # Once the loop is done, convert results to a DataFrame and store in session state
479
+ st.session_state['results_df'] = pd.DataFrame(results_list)
480
+ st.session_state['summary_df'] = pd.DataFrame(summary_list)
481
+
482
+ df_full = st.session_state['key1']
483
+ num_paragraphs = len(df_full['Vulnerability Label'])
484
+ num_references = len(df['Vulnerability Label'])
485
+
486
+ meta_list = []
487
+ # Store the Vulnerability Label and the response in a list of dictionaries
488
+ meta_list.append({
489
+ 'document': doc_name,
490
+ 'paragraphs': num_paragraphs,
491
+ 'references': num_references,
492
+ })
493
+
494
+ st.session_state['meta_df'] = pd.DataFrame(meta_list)
495
+
496
+ # Retrieve the results from session state
497
+ meta_df = st.session_state['meta_df']
498
+ summary_df = st.session_state['summary_df']
499
+ results_df = st.session_state['results_df']
500
+
501
+ # Use an in-memory buffer to hold the Excel file
502
+ excel_buffer = io.BytesIO()
503
+
504
+ # Create an Excel writer and write each DataFrame to a separate sheet
505
+ with pd.ExcelWriter(excel_buffer, engine='xlsxwriter') as writer:
506
+ meta_df.to_excel(writer, sheet_name='Meta', index=False)
507
+ summary_df.to_excel(writer, sheet_name='Summary', index=False)
508
+ results_df.to_excel(writer, sheet_name='Results', index=False)
509
+
510
+ # Ensure the buffer is ready for downloading
511
+ excel_buffer.seek(0)
512
+
513
+ # Create a download button for the Excel file
514
+ st.download_button(
515
+ label="Download LLM Evaluation",
516
+ data=excel_buffer,
517
+ file_name='eval_' + str.split(doc_name,".")[0] + '.xlsx',
518
+ mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
519
+ )
520
 
521
 
522
 
utils/__pycache__/__init__.cpython-310.pyc CHANGED
Binary files a/utils/__pycache__/__init__.cpython-310.pyc and b/utils/__pycache__/__init__.cpython-310.pyc differ
 
utils/__pycache__/config.cpython-310.pyc CHANGED
Binary files a/utils/__pycache__/config.cpython-310.pyc and b/utils/__pycache__/config.cpython-310.pyc differ
 
utils/__pycache__/preprocessing.cpython-310.pyc CHANGED
Binary files a/utils/__pycache__/preprocessing.cpython-310.pyc and b/utils/__pycache__/preprocessing.cpython-310.pyc differ
 
utils/__pycache__/vulnerability_classifier.cpython-310.pyc CHANGED
Binary files a/utils/__pycache__/vulnerability_classifier.cpython-310.pyc and b/utils/__pycache__/vulnerability_classifier.cpython-310.pyc differ