Wedyan2023 commited on
Commit
f031275
·
verified ·
1 Parent(s): 902f4eb

Create app102.py

Browse files
Files changed (1) hide show
  1. app102.py +1394 -0
app102.py ADDED
@@ -0,0 +1,1394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import os
4
+ import json
5
+ import base64
6
+ import random
7
+ from streamlit_pdf_viewer import pdf_viewer
8
+ from langchain.prompts import PromptTemplate
9
+ from datetime import datetime
10
+ from pathlib import Path
11
+ from openai import OpenAI
12
+ from dotenv import load_dotenv
13
+ import warnings
14
+
15
+ warnings.filterwarnings('ignore')
16
+
17
+ os.getenv("OAUTH_CLIENT_ID")
18
+
19
+
20
+ # Load environment variables and initialize the OpenAI client to use Hugging Face Inference API.
21
+ load_dotenv()
22
+ client = OpenAI(
23
+ base_url="https://api-inference.huggingface.co/v1",
24
+ api_key=os.environ.get('RAM') # Hugging Face API token
25
+ )
26
+
27
+ # Create necessary directories
28
+ for dir_name in ['data', 'feedback']:
29
+ if not os.path.exists(dir_name):
30
+ os.makedirs(dir_name)
31
+
32
+ # Custom CSS
33
+ st.markdown("""
34
+ <style>
35
+ .stButton > button {
36
+ width: 100%;
37
+ margin-bottom: 10px;
38
+ background-color: #4CAF50;
39
+ color: white;
40
+ border: none;
41
+ padding: 10px;
42
+ border-radius: 5px;
43
+ }
44
+ .task-button {
45
+ background-color: #2196F3 !important;
46
+ }
47
+ .stSelectbox {
48
+ margin-bottom: 20px;
49
+ }
50
+ .output-container {
51
+ padding: 20px;
52
+ border-radius: 5px;
53
+ border: 1px solid #ddd;
54
+ margin: 10px 0;
55
+ }
56
+ .status-container {
57
+ padding: 10px;
58
+ border-radius: 5px;
59
+ margin: 10px 0;
60
+ }
61
+ .sidebar-info {
62
+ padding: 10px;
63
+ background-color: #f0f2f6;
64
+ border-radius: 5px;
65
+ margin: 10px 0;
66
+ }
67
+ .feedback-button {
68
+ background-color: #ff9800 !important;
69
+ }
70
+ .feedback-container {
71
+ padding: 15px;
72
+ background-color: #f5f5f5;
73
+ border-radius: 5px;
74
+ margin: 15px 0;
75
+ }
76
+ </style>
77
+ """, unsafe_allow_html=True)
78
+
79
+ # Helper functions
80
+ def read_csv_with_encoding(file):
81
+ encodings = ['utf-8', 'latin1', 'iso-8859-1', 'cp1252']
82
+ for encoding in encodings:
83
+ try:
84
+ return pd.read_csv(file, encoding=encoding)
85
+ except UnicodeDecodeError:
86
+ continue
87
+ raise UnicodeDecodeError("Failed to read file with any supported encoding")
88
+
89
+ #def save_feedback(feedback_data):
90
+ #feedback_file = 'feedback/user_feedback.csv'
91
+ #feedback_df = pd.DataFrame([feedback_data])
92
+
93
+ #if os.path.exists(feedback_file):
94
+ #feedback_df.to_csv(feedback_file, mode='a', header=False, index=False)
95
+ #else:
96
+ #feedback_df.to_csv(feedback_file, index=False)
97
+
98
+ def reset_conversation():
99
+ st.session_state.conversation = []
100
+ st.session_state.messages = []
101
+ if 'task_choice' in st.session_state:
102
+ del st.session_state.task_choice
103
+ return None
104
+ #new 24 March
105
+ #user_input = st.text_input("Enter your prompt:")
106
+ ###########33
107
+
108
+ # Initialize session state variables
109
+ if "messages" not in st.session_state:
110
+ st.session_state.messages = []
111
+ if "examples_to_classify" not in st.session_state:
112
+ st.session_state.examples_to_classify = []
113
+ if "system_role" not in st.session_state:
114
+ st.session_state.system_role = ""
115
+
116
+
117
+
118
+ # Main app title
119
+ st.title("🤖🦙 Text Data Labeling and Generation App")
120
+ # def embed_pdf_sidebar(pdf_path):
121
+ # with open(pdf_path, "rb") as f:
122
+ # base64_pdf = base64.b64encode(f.read()).decode('utf-8')
123
+ # pdf_display = f"""
124
+ # <iframe src="data:application/pdf;base64,{base64_pdf}"
125
+ # width="100%" height="400" type="application/pdf"></iframe>
126
+ # """
127
+ # st.markdown(pdf_display, unsafe_allow_html=True)
128
+ #
129
+
130
+
131
+ # Sidebar settings
132
+ with st.sidebar:
133
+ st.title("⚙️ Settings")
134
+
135
+
136
+ #this last code works
137
+ with st.sidebar:
138
+ st.markdown("### 📘Data Generation and Labeling Instructions")
139
+ #st.markdown("<h4 style='color: #4A90E2;'>📘 Instructions</h4>", unsafe_allow_html=True)
140
+ with open("User instructions.pdf", "rb") as f:
141
+ st.download_button(
142
+ label="📄 Download Instructions PDF",
143
+ data=f,
144
+ #file_name="instructions.pdf",
145
+ file_name="User instructions.pdf",
146
+ mime="application/pdf"
147
+ )
148
+
149
+ selected_model = st.selectbox(
150
+ "Select Model",
151
+ ["meta-llama/Llama-3.3-70B-Instruct", "meta-llama/Llama-3.2-3B-Instruct","meta-llama/Llama-4-Scout-17B-16E-Instruct", "meta-llama/Meta-Llama-3-8B-Instruct",
152
+ "meta-llama/Llama-3.1-70B-Instruct"],
153
+ key='model_select'
154
+ )
155
+
156
+ temperature = st.slider(
157
+ "Temperature",
158
+ 0.0, 1.0, 0.7,
159
+ help="Controls randomness in generation"
160
+ )
161
+
162
+ st.button("🔄 New Conversation", on_click=reset_conversation)
163
+ with st.container():
164
+ st.markdown(f"""
165
+ <div class="sidebar-info">
166
+ <h4>Current Model: {selected_model}</h4>
167
+ <p><em>Note: Generated content may be inaccurate or false. Check important info.</em></p>
168
+ </div>
169
+ """, unsafe_allow_html=True)
170
+
171
+ feedback_url = "https://docs.google.com/forms/d/e/1FAIpQLSdZ_5mwW-pjqXHgxR0xriyVeRhqdQKgb5c-foXlYAV55Rilsg/viewform?usp=header"
172
+ st.sidebar.markdown(
173
+ f'<a href="{feedback_url}" target="_blank"><button style="width: 100%;">Feedback Form</button></a>',
174
+ unsafe_allow_html=True
175
+ )
176
+
177
+ # Display conversation
178
+ for message in st.session_state.messages:
179
+ with st.chat_message(message["role"]):
180
+ st.markdown(message["content"])
181
+
182
+ # Main content
183
+ if 'task_choice' not in st.session_state:
184
+ col1, col2 = st.columns(2)
185
+ with col1:
186
+ if st.button("📝 Data Generation", key="gen_button", help="Generate new data"):
187
+ st.session_state.task_choice = "Data Generation"
188
+ with col2:
189
+ if st.button("🏷️ Data Labeling", key="label_button", help="Label existing data"):
190
+ st.session_state.task_choice = "Data Labeling"
191
+
192
+ if "task_choice" in st.session_state:
193
+ if st.session_state.task_choice == "Data Generation":
194
+ st.header("📝 Data Generation")
195
+
196
+ # 1. Domain selection
197
+ domain_selection = st.selectbox("Domain", [
198
+ "Restaurant reviews", "E-Commerce reviews", "News", "AG News", "Tourism", "Custom"
199
+ ])
200
+
201
+ # 2. Handle custom domain input
202
+ custom_domain_valid = True # Assume valid until proven otherwise
203
+
204
+ if domain_selection == "Custom":
205
+ domain = st.text_input("Specify custom domain")
206
+ if not domain.strip():
207
+ st.error("Please specify a domain name.")
208
+ custom_domain_valid = False
209
+ else:
210
+ domain = domain_selection
211
+
212
+ # Classification type selection
213
+ classification_type = st.selectbox(
214
+ "Classification Type",
215
+ ["Sentiment Analysis", "Binary Classification", "Multi-Class Classification"]
216
+ )
217
+ # Labels setup based on classification type
218
+ #labels = []
219
+ labels = []
220
+ labels_valid = False
221
+ errors = []
222
+
223
+ def validate_binary_labels(labels):
224
+ errors = []
225
+ normalized = [label.strip().lower() for label in labels]
226
+
227
+ if not labels[0].strip():
228
+ errors.append("First class name is required.")
229
+ if not labels[1].strip():
230
+ errors.append("Second class name is required.")
231
+ if normalized[0] == normalized[1] and all(normalized):
232
+ errors.append("Class names must be different.")
233
+ return errors
234
+
235
+ if classification_type == "Sentiment Analysis":
236
+ st.write("### Sentiment Analysis Labels (Fixed)")
237
+ col1, col2, col3 = st.columns(3)
238
+ with col1:
239
+ st.text_input("First class", "Positive", disabled=True)
240
+ with col2:
241
+ st.text_input("Second class", "Negative", disabled=True)
242
+ with col3:
243
+ st.text_input("Third class", "Neutral", disabled=True)
244
+ labels = ["Positive", "Negative", "Neutral"]
245
+
246
+ elif classification_type == "Binary Classification":
247
+ st.write("### Binary Classification Labels")
248
+ col1, col2 = st.columns(2)
249
+ with col1:
250
+ label_1 = st.text_input("First class", "Positive")
251
+ with col2:
252
+ label_2 = st.text_input("Second class", "Negative")
253
+
254
+ labels = [label_1, label_2]
255
+ errors = validate_binary_labels(labels)
256
+
257
+ if errors:
258
+ st.error("\n".join(errors))
259
+ else:
260
+ st.success("Binary class names are valid and unique!")
261
+
262
+
263
+ elif classification_type == "Multi-Class Classification":
264
+ st.write("### Multi-Class Classification Labels")
265
+
266
+ default_labels_by_domain = {
267
+ "News": ["Political", "Sports", "Entertainment", "Technology", "Business"],
268
+ "AG News": ["World", "Sports", "Business", "Sci/Tech"],
269
+ "Tourism": ["Accommodation", "Transportation", "Tourist Attractions",
270
+ "Food & Dining", "Local Experience", "Adventure Activities",
271
+ "Wellness & Spa", "Eco-Friendly Practices", "Family-Friendly",
272
+ "Luxury Tourism"],
273
+ "Restaurant reviews": ["Italian", "French", "American"],
274
+ "E-Commerce reviews": ["Mobile Phones & Accessories", "Laptops & Computers","Kitchen & Dining",
275
+ "Beauty & Personal Care", "Home & Furniture", "Clothing & Fashion",
276
+ "Shoes & Handbags", "Health & Wellness", "Electronics & Gadgets",
277
+ "Books & Stationery","Toys & Games", "Sports & Fitness",
278
+ "Grocery & Gourmet Food","Watches & Accessories", "Baby Products"]
279
+ }
280
+
281
+ num_classes = st.slider("Number of classes", 3, 15, 3)
282
+
283
+ # Get defaults for selected domain, or empty list
284
+ defaults = default_labels_by_domain.get(domain, [])
285
+
286
+ labels = []
287
+ errors = []
288
+ cols = st.columns(3)
289
+
290
+ for i in range(num_classes):
291
+ with cols[i % 3]:
292
+ default_value = defaults[i] if i < len(defaults) else ""
293
+ label_input = st.text_input(f"Class {i+1}", default_value)
294
+ normalized_label = label_input.strip().title()
295
+
296
+ if not normalized_label:
297
+ errors.append(f"Class {i+1} name is required.")
298
+ else:
299
+ labels.append(normalized_label)
300
+
301
+ # Check for duplicates (case-insensitive)
302
+ if len(labels) != len(set(labels)):
303
+ errors.append("Labels names must be unique (case-insensitive, normalized to Title Case).")
304
+
305
+ # Show validation results
306
+ if errors:
307
+ for error in errors:
308
+ st.error(error)
309
+ else:
310
+ st.success("All Labels names are valid and unique!")
311
+ labels_valid = not errors # Will be True only if there are no label errors
312
+
313
+ ##############
314
+ #new 22/4/2025
315
+ # add additional attributes
316
+ add_attributes = st.checkbox("Add additional attributes (optional)")
317
+ additional_attributes = []
318
+
319
+ if add_attributes:
320
+ num_attributes = st.slider("Number of attributes to add", 1, 5, 1)
321
+ for i in range(num_attributes):
322
+ st.markdown(f"#### Attribute {i+1}")
323
+ attr_name = st.text_input(f"Name of attribute {i+1}", key=f"attr_name_{i}")
324
+ attr_topics = st.text_input(f"Topics (comma-separated) for {attr_name}", key=f"attr_topics_{i}")
325
+ if attr_name and attr_topics:
326
+ topics_list = [topic.strip() for topic in attr_topics.split(",") if topic.strip()]
327
+ additional_attributes.append({"attribute": attr_name, "topics": topics_list})
328
+
329
+ ################
330
+
331
+ # Generation parameters
332
+ col1, col2 = st.columns(2)
333
+ with col1:
334
+ min_words = st.number_input("Min words", 1, 100, 20)
335
+ with col2:
336
+ max_words = st.number_input("Max words", min_words, 100, 50)
337
+
338
+ # Few-shot examples
339
+ use_few_shot = st.toggle("Use few-shot examples")
340
+ few_shot_examples = []
341
+ if use_few_shot:
342
+ num_examples = st.slider("Number of few-shot examples", 1, 10, 1)
343
+ for i in range(num_examples):
344
+ with st.expander(f"Example {i+1}"):
345
+ content = st.text_area(f"Content", key=f"few_shot_content_{i}")
346
+ label = st.selectbox(f"Label", labels, key=f"few_shot_label_{i}")
347
+ if content and label:
348
+ few_shot_examples.append({"content": content, "label": label})
349
+
350
+ num_to_generate = st.number_input("Number of examples", 1, 200, 10)
351
+ #sytem role after
352
+ # System role customization
353
+ #default_system_role = f"You are a professional {classification_type} expert, your role is to generate text examples for {domain} domain. Always generate unique diverse examples and do not repeat the generated data. The generated text should be between {min_words} to {max_words} words long."
354
+ # System role customization
355
+ default_system_role = (
356
+ f"You are a seasoned expert in {classification_type}, specializing in the {domain} domain. "
357
+ f" Your primary responsibility is to generate high-quality, diverse, and unique text examples "
358
+ f"tailored to this domain. Please ensure that each example adheres to the specified length "
359
+ f"requirements, ranging from {min_words} to {max_words} words, and avoid any repetition in the generated content."
360
+ )
361
+ system_role = st.text_area("Modify System Role (optional)",
362
+ value=default_system_role,
363
+ key="system_role_input")
364
+ st.session_state['system_role'] = system_role if system_role else default_system_role
365
+ # Labels initialization
366
+ #labels = []
367
+
368
+
369
+ user_prompt = st.text_area("User Prompt (optional)")
370
+
371
+ # Updated prompt template including system role
372
+ prompt_template = PromptTemplate(
373
+ input_variables=["system_role", "classification_type", "domain", "num_examples",
374
+ "min_words", "max_words", "labels", "user_prompt", "few_shot_examples", "additional_attributes"],
375
+ template=(
376
+ "{system_role}\n"
377
+ "- Use the following parameters:\n"
378
+ "- Generate {num_examples} examples\n"
379
+ "- Each example should be between {min_words} to {max_words} words long\n"
380
+ "- Use these labels: {labels}.\n"
381
+ "- Use the following additional attributes:\n"
382
+ "- {additional_attributes}\n"
383
+ "- Generate the examples in this format: 'Example text. Label: label'\n"
384
+ "- Do not include word counts or any additional information\n"
385
+ "- Always use your creativity and intelligence to generate unique and diverse text data\n"
386
+ "- In sentiment analysis, ensure that the sentiment classification is clearly identified as Positive, Negative, or Neutral. Do not leave the sentiment ambiguous.\n"
387
+ "- Write unique examples every time.\n"
388
+ "- DO NOT REPEAT your gnerated text. \n"
389
+ "- For each Output, describe it once and move to the next.\n"
390
+ "- List each Output only once, and avoid repeating details.\n"
391
+ "- Additional instructions: {user_prompt}\n\n"
392
+ "- Use the following examples as a reference in the generation process\n\n {few_shot_examples}. \n"
393
+ "- Think step by step, generate numbered examples, and check each newly generated example to ensure it has not been generated before. If it has, modify it"
394
+
395
+ )
396
+ )
397
+ # template=(
398
+ # "{system_role}\n"
399
+ # "- Use the following parameters:\n"
400
+ # "- Generate {num_examples} examples\n"
401
+ # "- Each example should be between {min_words} to {max_words} words long\n"
402
+ # "- Use these labels: {labels}.\n"
403
+ # "- Use the following additional attributes:\n"
404
+ # "{additional_attributes}\n"
405
+ # #"- Format each example like this: 'Example text. Label: [label]. Attribute1: [topic1]. Attribute2: [topic2]'\n"
406
+ # "- Generate the examples in this format: 'Example text. Label: label'\n"
407
+ # "- Additional instructions: {user_prompt}\n"
408
+ # "- Use these few-shot examples if provided:\n{few_shot_examples}\n"
409
+ # "- Think step by step and ensure examples are unique and not repeated."
410
+ # )
411
+ # )
412
+ ##########new 22/4/2025
413
+ formatted_attributes = "\n".join([
414
+ f"- {attr['attribute']}: {', '.join(attr['topics'])}" for attr in additional_attributes
415
+ ])
416
+ #######################
417
+
418
+ # Generate system prompt
419
+ system_prompt = prompt_template.format(
420
+ system_role=st.session_state['system_role'],
421
+ classification_type=classification_type,
422
+ domain=domain,
423
+ num_examples=num_to_generate,
424
+ min_words=min_words,
425
+ max_words=max_words,
426
+ labels=", ".join(labels),
427
+ user_prompt=user_prompt,
428
+ few_shot_examples="\n".join([f"{ex['content']}\nLabel: {ex['label']}" for ex in few_shot_examples]) if few_shot_examples else "",
429
+ additional_attributes=formatted_attributes
430
+ )
431
+
432
+
433
+ # Store system prompt in session state
434
+ st.session_state['system_prompt'] = system_prompt
435
+
436
+ # Display system prompt
437
+ st.write("System Prompt:")
438
+ st.text_area("Current System Prompt", value=st.session_state['system_prompt'],
439
+ height=400, disabled=True)
440
+
441
+
442
+ if st.button("🎯 Generate Examples"):
443
+ #
444
+ errors = []
445
+ if domain_selection == "Custom" and not domain.strip():
446
+ st.warning("Custom domain name is required.")
447
+ elif len(labels) != len(set(labels)):
448
+ st.warning("Class names must be unique.")
449
+ elif any(not lbl.strip() for lbl in labels):
450
+ st.warning("All class labels must be filled in.")
451
+ #else:
452
+ #st.success("Generating examples for domain: {domain}")
453
+
454
+ #if not custom_domain_valid:
455
+ #st.warning("Custom domain name is required.")
456
+ #elif not labels_valid:
457
+ #st.warning("Please fix the label errors before generating examples.")
458
+ #else:
459
+ # Proceed to generate examples
460
+ #st.success(f"Generating examples for domain: {domain}")
461
+
462
+ with st.spinner("Generating examples..."):
463
+ try:
464
+ stream = client.chat.completions.create(
465
+ model=selected_model,
466
+ messages=[{"role": "system", "content": st.session_state['system_prompt']}],
467
+ temperature=temperature,
468
+ stream=True,
469
+ max_tokens=80000,
470
+ top_p=0.9,
471
+ # repetition_penalty=1.2,
472
+ #frequency_penalty=0.5, # Discourages frequent words
473
+ #presence_penalty=0.6,
474
+ )
475
+ #st.session_state['system_prompt'] = system_prompt
476
+ #new 24 march
477
+ st.session_state.messages.append({"role": "user", "content": system_prompt})
478
+ # # ####################
479
+ response = st.write_stream(stream)
480
+ st.session_state.messages.append({"role": "assistant", "content": response})
481
+ # Initialize session state variables if they don't exist
482
+ if 'system_prompt' not in st.session_state:
483
+ st.session_state.system_prompt = system_prompt
484
+
485
+ if 'response' not in st.session_state:
486
+ st.session_state.response = response
487
+
488
+ if 'generated_examples' not in st.session_state:
489
+ st.session_state.generated_examples = []
490
+
491
+ if 'generated_examples_csv' not in st.session_state:
492
+ st.session_state.generated_examples_csv = None
493
+
494
+ if 'generated_examples_json' not in st.session_state:
495
+ st.session_state.generated_examples_json = None
496
+
497
+ # Parse response and generate examples list
498
+ examples_list = []
499
+ for line in response.split('\n'):
500
+ if line.strip():
501
+ parts = line.rsplit('Label:', 1)
502
+ if len(parts) == 2:
503
+ text = parts[0].strip()
504
+ label = parts[1].strip()
505
+ if text and label:
506
+ examples_list.append({
507
+ 'text': text,
508
+ 'label': label,
509
+ 'system_prompt': st.session_state.system_prompt,
510
+ 'system_role': st.session_state.system_role,
511
+ 'task_type': 'Data Generation',
512
+ 'Use few-shot example?': 'Yes' if use_few_shot else 'No',
513
+ })
514
+
515
+ # example_dict = {
516
+ # 'text': text,
517
+ # 'label': label,
518
+ # 'system_prompt': st.session_state.system_prompt,
519
+ # 'system_role': st.session_state.system_role,
520
+ # 'task_type': 'Data Generation',
521
+ # 'Use few-shot example?': 'Yes' if use_few_shot else 'No',
522
+ # }
523
+ # for attr in additional_attributes:
524
+ # example_dict[attr['attribute']] = random.choice(attr['topics'])
525
+
526
+ # examples_list.append(example_dict)
527
+
528
+
529
+ if examples_list:
530
+ # Update session state with new data
531
+ st.session_state.generated_examples = examples_list
532
+
533
+ # Generate CSV and JSON data
534
+ df = pd.DataFrame(examples_list)
535
+ st.session_state.generated_examples_csv = df.to_csv(index=False).encode('utf-8')
536
+ st.session_state.generated_examples_json = json.dumps(examples_list, indent=2).encode('utf-8')
537
+
538
+ # Vertical layout with centered "or" between buttons
539
+ st.download_button(
540
+ "📥 Download Generated Examples (CSV)",
541
+ st.session_state.generated_examples_csv,
542
+ "generated_examples.csv",
543
+ "text/csv",
544
+ key='download-csv-persistent'
545
+ )
546
+
547
+ # Add space and center the "or"
548
+ st.markdown("""
549
+ <div style='text-align: left; margin:15px 0; font-weight: 600; color: #666;'>. . . . . . or</div>
550
+ """, unsafe_allow_html=True)
551
+
552
+ st.download_button(
553
+ "📥 Download Generated Examples (JSON)",
554
+ st.session_state.generated_examples_json,
555
+ "generated_examples.json",
556
+ "application/json",
557
+ key='download-json-persistent'
558
+ )
559
+ # # Display the labeled examples
560
+ # st.markdown("##### 📋 Labeled Examples Preview")
561
+ # st.dataframe(df, use_container_width=True)
562
+
563
+ if st.button("Continue"):
564
+ if follow_up == "Generate more examples":
565
+ st.experimental_rerun()
566
+ elif follow_up == "Data Labeling":
567
+ st.session_state.task_choice = "Data Labeling"
568
+ st.experimental_rerun()
569
+
570
+ except Exception as e:
571
+ st.error("An error occurred during generation.")
572
+ st.error(f"Details: {e}")
573
+
574
+
575
+ # Lableing Process
576
+ elif st.session_state.task_choice == "Data Labeling":
577
+ st.header("🏷️ Data Labeling")
578
+
579
+ domain_selection = st.selectbox("Domain", ["Restaurant reviews", "E-Commerce reviews", "News", "AG News", "Tourism", "Custom"])
580
+ # 2. Handle custom domain input
581
+ custom_domain_valid = True # Assume valid until proven otherwise
582
+
583
+ if domain_selection == "Custom":
584
+ domain = st.text_input("Specify custom domain")
585
+ if not domain.strip():
586
+ st.error("Please specify a domain name.")
587
+ custom_domain_valid = False
588
+ else:
589
+ domain = domain_selection
590
+
591
+
592
+ # Classification type selection
593
+ classification_type = st.selectbox(
594
+ "Classification Type",
595
+ ["Sentiment Analysis", "Binary Classification", "Multi-Class Classification", "Named Entity Recognition (NER)"]
596
+ )
597
+ #NNew edit
598
+ # Labels setup based on classification type
599
+ labels = []
600
+ labels_valid = False
601
+ errors = []
602
+
603
+ if classification_type == "Sentiment Analysis":
604
+ st.write("### Sentiment Analysis Labels (Fixed)")
605
+ col1, col2, col3 = st.columns(3)
606
+ with col1:
607
+ label_1 = st.text_input("First class", "Positive", disabled=True)
608
+ with col2:
609
+ label_2 = st.text_input("Second class", "Negative", disabled=True)
610
+ with col3:
611
+ label_3 = st.text_input("Third class", "Neutral", disabled=True)
612
+ labels = ["Positive", "Negative", "Neutral"]
613
+
614
+
615
+ elif classification_type == "Binary Classification":
616
+ st.write("### Binary Classification Labels")
617
+ col1, col2 = st.columns(2)
618
+
619
+ with col1:
620
+ label_1 = st.text_input("First class", "Positive")
621
+ with col2:
622
+ label_2 = st.text_input("Second class", "Negative")
623
+
624
+ errors = []
625
+ labels = [label_1.strip(), label_2.strip()]
626
+
627
+
628
+ # Strip and lower-case labels for validation
629
+ label_1 = labels[0].strip()
630
+ label_2 = labels[1].strip()
631
+
632
+ # Check for empty class names
633
+ if not label_1:
634
+ errors.append("First class name is required.")
635
+ if not label_2:
636
+ errors.append("Second class name is required.")
637
+
638
+ # Check for duplicates (case insensitive)
639
+ if label_1.lower() == label_2.lower() and label_1 and label_2:
640
+ errors.append("Class names must be different.")
641
+
642
+ # Show errors or success
643
+ if errors:
644
+ for error in errors:
645
+ st.error(error)
646
+ else:
647
+ st.success("Binary class names are valid and unique!")
648
+
649
+
650
+ elif classification_type == "Multi-Class Classification":
651
+ st.write("### Multi-Class Classification Labels")
652
+
653
+ default_labels_by_domain = {
654
+ "News": ["Political", "Sports", "Entertainment", "Technology", "Business"],
655
+ "AG News": ["World", "Sports", "Business", "Sci/Tech"],
656
+ "Tourism": ["Accommodation", "Transportation", "Tourist Attractions",
657
+ "Food & Dining", "Local Experience", "Adventure Activities",
658
+ "Wellness & Spa", "Eco-Friendly Practices", "Family-Friendly",
659
+ "Luxury Tourism"],
660
+ "Restaurant reviews": ["Italian", "French", "American"],
661
+ "E-Commerce reviews": ["Mobile Phones & Accessories", "Laptops & Computers","Kitchen & Dining",
662
+ "Beauty & Personal Care", "Home & Furniture", "Clothing & Fashion",
663
+ "Shoes & Handbags", "Health & Wellness", "Electronics & Gadgets",
664
+ "Books & Stationery","Toys & Games", "Sports & Fitness",
665
+ "Grocery & Gourmet Food","Watches & Accessories", "Baby Products"]
666
+ }
667
+
668
+
669
+
670
+ # Ask user how many classes they want to define
671
+ num_classes = st.slider("Select the number of classes (labels)", min_value=3, max_value=10, value=3)
672
+
673
+ # Use default labels based on selected domain, if available
674
+ defaults = default_labels_by_domain.get(domain, [])
675
+
676
+ labels = []
677
+ errors = []
678
+ cols = st.columns(3) # For nicely arranged label inputs
679
+
680
+ for i in range(num_classes):
681
+ with cols[i % 3]: # Distribute inputs across columns
682
+ default_value = defaults[i] if i < len(defaults) else ""
683
+ label_input = st.text_input(f"Label {i + 1}", default_value)
684
+ normalized_label = label_input.strip().title()
685
+
686
+ if not normalized_label:
687
+ errors.append(f"Label {i + 1} is required.")
688
+ else:
689
+ labels.append(normalized_label)
690
+
691
+ # Check for duplicates (case-insensitive)
692
+ normalized_set = {label.lower() for label in labels}
693
+ if len(labels) != len(normalized_set):
694
+ errors.append("Label names must be unique (case-insensitive).")
695
+
696
+ # Show validation results
697
+ if errors:
698
+ for error in errors:
699
+ st.error(error)
700
+ else:
701
+ st.success("All label names are valid and unique!")
702
+
703
+ labels_valid = not errors # True if no validation errors
704
+
705
+ elif classification_type == "Named Entity Recognition (NER)":
706
+ # # NER entity options
707
+ # ner_entities = [
708
+ # "PERSON - Names of people, fictional characters, historical figures",
709
+ # "ORG - Companies, institutions, agencies, teams",
710
+ # "LOC - Physical locations (mountains, oceans, etc.)",
711
+ # "GPE - Countries, cities, states, political regions",
712
+ # "DATE - Calendar dates, years, centuries",
713
+ # "TIME - Times, durations",
714
+ # "MONEY - Monetary values with currency"
715
+ # ]
716
+ # selected_entities = st.multiselect(
717
+ # "Select entities to recognize",
718
+ # ner_entities,
719
+ # default=["PERSON - Names of people, fictional characters, historical figures",
720
+ # "ORG - Companies, institutions, agencies, teams",
721
+ # "LOC - Physical locations (mountains, oceans, etc.)",
722
+ # "GPE - Countries, cities, states, political regions",
723
+ # "DATE - Calendar dates, years, centuries",
724
+ # "TIME - Times, durations",
725
+ # "MONEY - Monetary values with currency"],
726
+ # key="ner_entity_selection"
727
+ # )
728
+ #new 22/4/2025
729
+ #if classification_type == "Named Entity Recognition (NER)":
730
+ use_few_shot = True
731
+ #new 22/4/2025
732
+ few_shot_examples = [
733
+ {"content": "Mount Everest is the tallest mountain in the world.", "label": "LOC: Mount Everest"},
734
+ {"content": "The President of the United States visited Paris last summer.", "label": "GPE: United States, GPE: Paris"},
735
+ {"content": "Amazon is expanding its offices in Berlin.", "label": "ORG: Amazon, GPE: Berlin"},
736
+ {"content": "J.K. Rowling wrote the Harry Potter books.", "label": "PERSON: J.K. Rowling"},
737
+ {"content": "Apple was founded in California in 1976.", "label": "ORG: Apple, GPE: California, DATE: 1976"},
738
+ {"content": "The Nile is the longest river in Africa.", "label": "LOC: Nile, GPE: Africa"},
739
+ {"content": "He arrived at 3 PM for the meeting.", "label": "TIME: 3 PM"},
740
+ {"content": "She bought the dress for $200.", "label": "MONEY: $200"},
741
+ {"content": "The event is scheduled for July 4th.", "label": "DATE: July 4th"},
742
+ {"content": "The World Health Organization is headquartered in Geneva.", "label": "ORG: World Health Organization, GPE: Geneva"}
743
+ ]
744
+ ###########
745
+
746
+ st.write("### Named Entity Recognition (NER) Entities")
747
+
748
+ # Predefined standard entities
749
+ ner_entities = [
750
+ "PERSON - Names of people, fictional characters, historical figures",
751
+ "ORG - Companies, institutions, agencies, teams",
752
+ "LOC - Physical locations (mountains, oceans, etc.)",
753
+ "GPE - Countries, cities, states, political regions",
754
+ "DATE - Calendar dates, years, centuries",
755
+ "TIME - Times, durations",
756
+ "MONEY - Monetary values with currency"
757
+ ]
758
+
759
+ # User can add custom NER types
760
+ custom_ner_entities = []
761
+ if st.checkbox("Add custom NER entities?"):
762
+ num_custom_ner = st.slider("Number of custom NER entities", 1, 10, 1)
763
+ for i in range(num_custom_ner):
764
+ st.markdown(f"#### Custom Entity {i+1}")
765
+ custom_type = st.text_input(f"Entity type {i+1}", key=f"custom_ner_type_{i}")
766
+ custom_description = st.text_input(f"Description for {custom_type}", key=f"custom_ner_desc_{i}")
767
+ if custom_type and custom_description:
768
+ custom_ner_entities.append(f"{custom_type.upper()} - {custom_description}")
769
+
770
+ # Combine built-in and custom NERs
771
+ all_ner_options = ner_entities + custom_ner_entities
772
+
773
+ selected_entities = st.multiselect(
774
+ "Select entities to recognize",
775
+ all_ner_options,
776
+ default=ner_entities
777
+ )
778
+
779
+ # Extract entity type names (before the dash)
780
+ labels = [entity.split(" - ")[0].strip() for entity in selected_entities]
781
+
782
+ if not labels:
783
+ st.warning("Please select at least one entity type.")
784
+ labels = ["PERSON"]
785
+
786
+ ##########
787
+
788
+ # # Extract just the entity type (before the dash)
789
+ # labels = [entity.split(" - ")[0] for entity in selected_entities]
790
+
791
+ # if not labels:
792
+ # st.warning("Please select at least one entity type")
793
+ # labels = ["PERSON"] # Default if nothing selected
794
+
795
+
796
+
797
+
798
+
799
+ #NNew edit
800
+ # elif classification_type == "Multi-Class Classification":
801
+ # st.write("### Multi-Class Classification Labels")
802
+
803
+ # default_labels_by_domain = {
804
+ # "News": ["Political", "Sports", "Entertainment", "Technology", "Business"],
805
+ # "AG News": ["World", "Sports", "Business", "Sci/Tech"],
806
+ # "Tourism": ["Accommodation", "Transportation", "Tourist Attractions",
807
+ # "Food & Dining", "Local Experience", "Adventure Activities",
808
+ # "Wellness & Spa", "Eco-Friendly Practices", "Family-Friendly",
809
+ # "Luxury Tourism"],
810
+ # "Restaurant reviews": ["Italian", "French", "American"]
811
+ # }
812
+ # num_classes = st.slider("Number of classes", 3, 10, 3)
813
+
814
+ # # Get defaults for selected domain, or empty list
815
+ # defaults = default_labels_by_domain.get(domain, [])
816
+
817
+ # labels = []
818
+ # errors = []
819
+ # cols = st.columns(3)
820
+
821
+ # for i in range(num_classes):
822
+ # with cols[i % 3]:
823
+ # default_value = defaults[i] if i < len(defaults) else ""
824
+ # label_input = st.text_input(f"Class {i+1}", default_value)
825
+ # normalized_label = label_input.strip().title()
826
+
827
+ # if not normalized_label:
828
+ # errors.append(f"Class {i+1} name is required.")
829
+ # else:
830
+ # labels.append(normalized_label)
831
+
832
+ # # Check for duplicates (case-insensitive)
833
+ # if len(labels) != len(set(labels)):
834
+ # errors.append("Labels names must be unique (case-insensitive, normalized to Title Case).")
835
+
836
+ # # Show validation results
837
+ # if errors:
838
+ # for error in errors:
839
+ # st.error(error)
840
+ # else:
841
+ # st.success("All Labels names are valid and unique!")
842
+ # labels_valid = not errors # Will be True only if there are no label errors
843
+
844
+
845
+
846
+
847
+ # else:
848
+ # num_classes = st.slider("Number of classes", 3, 23, 3, key="label_num_classes")
849
+ # labels = []
850
+ # cols = st.columns(3)
851
+ # for i in range(num_classes):
852
+ # with cols[i % 3]:
853
+ # label = st.text_input(f"Class {i+1}", f"Class_{i+1}", key=f"label_class_{i}")
854
+ # labels.append(label)
855
+
856
+ use_few_shot = st.toggle("Use few-shot examples for labeling")
857
+ few_shot_examples = []
858
+ if use_few_shot:
859
+ num_few_shot = st.slider("Number of few-shot examples", 1, 10, 1)
860
+ for i in range(num_few_shot):
861
+ with st.expander(f"Few-shot Example {i+1}"):
862
+ content = st.text_area(f"Content", key=f"label_few_shot_content_{i}")
863
+ label = st.selectbox(f"Label", labels, key=f"label_few_shot_label_{i}")
864
+ if content and label:
865
+ few_shot_examples.append(f"{content}\nLabel: {label}")
866
+
867
+ num_examples = st.number_input("Number of examples to classify", 1, 100, 1)
868
+
869
+ examples_to_classify = []
870
+ if num_examples <= 20:
871
+ for i in range(num_examples):
872
+ example = st.text_area(f"Example {i+1}", key=f"example_{i}")
873
+ if example:
874
+ examples_to_classify.append(example)
875
+ else:
876
+ examples_text = st.text_area(
877
+ "Enter examples (one per line)",
878
+ height=300,
879
+ help="Enter each example on a new line"
880
+ )
881
+ if examples_text:
882
+ examples_to_classify = [ex.strip() for ex in examples_text.split('\n') if ex.strip()]
883
+ if len(examples_to_classify) > num_examples:
884
+ examples_to_classify = examples_to_classify[:num_examples]
885
+
886
+ #New Wedyan
887
+ #default_system_role = f"You are a professional {classification_type} expert, your role is to classify the provided text examples for {domain} domain."
888
+ # System role customization
889
+ default_system_role = (f"You are a highly skilled {classification_type} expert."
890
+ f" Your task is to accurately classify the provided text examples within the {domain} domain."
891
+ f" Ensure that all classifications are precise, context-aware, and aligned with domain-specific standards and best practices."
892
+ )
893
+ system_role = st.text_area("Modify System Role (optional)",
894
+ value=default_system_role,
895
+ key="system_role_input")
896
+ st.session_state['system_role'] = system_role if system_role else default_system_role
897
+ # Labels initialization
898
+ #labels = []
899
+ ####
900
+
901
+ user_prompt = st.text_area("User prompt (optional)", key="label_instructions")
902
+
903
+ few_shot_text = "\n\n".join(few_shot_examples) if few_shot_examples else ""
904
+ examples_text = "\n".join([f"{i+1}. {ex}" for i, ex in enumerate(examples_to_classify)])
905
+
906
+ # Customize prompt template based on classification type
907
+ if classification_type == "Named Entity Recognition (NER)":
908
+ # label_prompt_template = PromptTemplate(
909
+ # input_variables=["system_role", "labels", "few_shot_examples", "examples", "domain", "user_prompt"],
910
+ # template=(
911
+ # "{system_role}\n"
912
+ # #"- You are a professional Named Entity Recognition (NER) expert in {domain} domain. Your role is to identify and extract the following entity types: {labels}.\n"
913
+ # "- For each text example provided, identify all entities of the requested types.\n"
914
+ # "- Use the following entities: {labels}.\n"
915
+ # "- Return each example followed by the entities you found in this format: 'Example text.\n \n Entities:\n [ENTITY_TYPE: entity text\n\n, ENTITY_TYPE: entity text\n\n, ...] or [No entities found]'\n"
916
+ # "- If no entities of the requested types are found, indicate 'No entities found' in this text.\n"
917
+ # "- Be precise about entity boundaries - don't include unnecessary words.\n"
918
+ # "- Do not provide any additional information or explanations.\n"
919
+ # "- Additional instructions:\n {user_prompt}\n\n"
920
+ # "- Use user few-shot examples as guidance if provided:\n{few_shot_examples}\n\n"
921
+ # "- Examples to analyze:\n{examples}\n\n"
922
+ # "Output:\n"
923
+ # )
924
+ # )
925
+ #new 22/4/2025
926
+ # label_prompt_template = PromptTemplate(
927
+ # input_variables=["system_role", "labels", "few_shot_examples", "examples", "domain", "user_prompt"],
928
+ # template=(
929
+ # "{system_role}\n"
930
+ # "- You are performing Named Entity Recognition (NER) in the domain of {domain}.\n"
931
+ # "- Use the following entity types: {labels}.\n\n"
932
+ # "### Reasoning Steps:\n"
933
+ # "1. Read the example carefully.\n"
934
+ # "2. For each named entity mentioned, determine its meaning and role in the sentence.\n"
935
+ # "3. Think about the **context**: Is it a physical location (LOC)? A geopolitical region (GPE)? A person (PERSON)?\n"
936
+ # "4. Based on the definition of each label, assign the most **specific and correct** label.\n\n"
937
+ # "For example:\n"
938
+ # "- 'Mount Everest' → LOC (it's a mountain)\n"
939
+ # "- 'France' → GPE (it's a country)\n"
940
+ # "- 'Microsoft' → ORG\n"
941
+ # "- 'John Smith' → PERSON\n\n"
942
+ # "- Return each example followed by the entities you found in this format:\n"
943
+ # "'Example text.'\nEntities: [ENTITY_TYPE: entity text, ENTITY_TYPE: entity text, ...] or [No entities found]\n"
944
+ # "- If no entities of the requested types are found, return 'No entities found'.\n"
945
+ # "- Be precise about entity boundaries - don't include extra words.\n"
946
+ # "- Do not explain or justify your answers.\n\n"
947
+ # "Additional instructions:\n{user_prompt}\n\n"
948
+ # "Few-shot examples:\n{few_shot_examples}\n\n"
949
+ # "Examples to label:\n{examples}\n"
950
+ # "Output:\n"
951
+ # )
952
+ #)
953
+ # label_prompt_template = PromptTemplate(
954
+ # input_variables=["system_role", "labels", "few_shot_examples", "examples", "domain", "user_prompt"],
955
+ # template=(
956
+ # "{system_role}\n"
957
+ # "- You are an expert at Named Entity Recognition (NER) for domain: {domain}.\n"
958
+ # "- Use these entity types: {labels}.\n\n"
959
+ # "### Output Format:\n"
960
+ # # "Return each example followed by the entities you found in this format: 'Example text.\n Entities:\n [ENTITY_TYPE: entity text\n\"
961
+ # "Return each example followed by the entities you found in this format: 'Example text.\n 'Entity types:\n "Then group the entities under each label like this:\n" "
962
+ # #"Then Start with this line exactly: 'Entity types\n'\n"
963
+ # #"Then group the entities under each label like this:\n"
964
+ # "\n PERSON – Angela Merkel, John Smith\n\n"
965
+ # "\ ORG – Google, United Nations\n\n"
966
+ # "\n DATE – January 1st, 2023\n\n"
967
+ # "\n ... and so on.\n\n"
968
+ # "If entity {labels} not found, do not write it in your response\n"
969
+ # "- Do NOT output them inline after the text.\n"
970
+ # "- Do NOT repeat the sentence.\n"
971
+ # "- If no entities are found for a type, skip it.\n"
972
+ # "- Keep the format consistent.\n\n"
973
+ # "User Instructions:\n{user_prompt}\n\n"
974
+ # "Few-shot Examples:\n{few_shot_examples}\n\n"
975
+ # "Examples to analyze:\n{examples}"
976
+ # )
977
+ # )
978
+
979
+
980
+ label_prompt_template = PromptTemplate(
981
+ input_variables=["system_role", "labels", "few_shot_examples", "examples", "domain", "user_prompt"],
982
+ template=(
983
+ "{system_role}\n"
984
+ "- You are an expert at Named Entity Recognition (NER) for domain: {domain}.\n"
985
+ "- Use these entity types: {labels}.\n\n"
986
+ "### Output Format:\n"
987
+ "Return each example followed by the entities you found in this format:\n"
988
+ "'Example text.\n \n and in new line Entity types:\n"
989
+ "Then group the entities under each label like this:\n"
990
+ "\nPERSON – Angela Merkel, John Smith\n"
991
+ "ORG – Google, United Nations\n"
992
+ "DATE – January 1st, 2023\n"
993
+ "... and so on.\n\n"
994
+ "Each new entities group should be in a new line.\n"
995
+ "If entity type {labels} is not found, do not write it in your response.\n"
996
+ "- Do NOT output them inline after the text.\n"
997
+ "- Do NOT repeat the sentence.\n"
998
+ "- If no entities are found for a type, skip it.\n"
999
+ "- Keep the format consistent.\n\n"
1000
+ "User Instructions:\n{user_prompt}\n\n"
1001
+ "Few-shot Examples:\n{few_shot_examples}\n\n"
1002
+ "Examples to analyze:\n{examples}"
1003
+ )
1004
+ )
1005
+
1006
+ #######
1007
+ else:
1008
+ label_prompt_template = PromptTemplate(
1009
+
1010
+ input_variables=["system_role", "classification_type", "labels", "few_shot_examples", "examples","domain", "user_prompt"],
1011
+ template=(
1012
+ #"- Let'\s think step by step:"
1013
+ "{system_role}\n"
1014
+ # "- You are a professional {classification_type} expert in {domain} domain. Your role is to classify the following examples using these labels: {labels}.\n"
1015
+ "- Use the following instructions:\n"
1016
+ "- Use the following labels: {labels}.\n"
1017
+ "- Return the classified text followed by the label in this format: 'text. Label: [label]'\n"
1018
+ "- Do not provide any additional information or explanations\n"
1019
+ "- User prompt:\n {user_prompt}\n\n"
1020
+ "- Use user provided examples as guidence in the classification process:\n\n {few_shot_examples}\n"
1021
+ "- Examples to classify:\n{examples}\n\n"
1022
+ "- Think step by step then classify the examples"
1023
+ #"Output:\n"
1024
+ ))
1025
+
1026
+ # Check if few_shot_examples is already a formatted string
1027
+ # Check if few_shot_examples is already a formatted string
1028
+ if isinstance(few_shot_examples, str):
1029
+ formatted_few_shot = few_shot_examples
1030
+ # If it's a list of already formatted strings
1031
+ elif isinstance(few_shot_examples, list) and all(isinstance(ex, str) for ex in few_shot_examples):
1032
+ formatted_few_shot = "\n".join(few_shot_examples)
1033
+ # If it's a list of dictionaries with 'content' and 'label' keys
1034
+ elif isinstance(few_shot_examples, list) and all(isinstance(ex, dict) and 'content' in ex and 'label' in ex for ex in few_shot_examples):
1035
+ formatted_few_shot = "\n".join([f"{ex['content']}\nLabel: {ex['label']}" for ex in few_shot_examples])
1036
+ else:
1037
+ formatted_few_shot = ""
1038
+ # #new 22/4/2025
1039
+ # few_shot_examples = [
1040
+ # {"content": "Mount Everest is the tallest mountain in the world.", "label": "LOC: Mount Everest"},
1041
+ # {"content": "The President of the United States visited Paris last summer.", "label": "GPE: United States, GPE: Paris"},
1042
+ # {"content": "Amazon is expanding its offices in Berlin.", "label": "ORG: Amazon, GPE: Berlin"},
1043
+ # {"content": "J.K. Rowling wrote the Harry Potter books.", "label": "PERSON: J.K. Rowling"},
1044
+ # {"content": "Apple was founded in California in 1976.", "label": "ORG: Apple, GPE: California, DATE: 1976"},
1045
+ # {"content": "The Nile is the longest river in Africa.", "label": "LOC: Nile, GPE: Africa"},
1046
+ # {"content": "He arrived at 3 PM for the meeting.", "label": "TIME: 3 PM"},
1047
+ # {"content": "She bought the dress for $200.", "label": "MONEY: $200"},
1048
+ # {"content": "The event is scheduled for July 4th.", "label": "DATE: July 4th"},
1049
+ # {"content": "The World Health Organization is headquartered in Geneva.", "label": "ORG: World Health Organization, GPE: Geneva"}
1050
+ # ]
1051
+ # ###########
1052
+ # new 22/4/2025
1053
+ #formatted_few_shot = "\n".join([f"{ex['content']}\nEntities: [{ex['label']}]" for ex in few_shot_examples])
1054
+ formatted_few_shot = "\n\n".join([f"{ex['content']}\n\nEntity types\n{ex['label']}" for ex in few_shot_examples])
1055
+
1056
+ ###########
1057
+ system_prompt = label_prompt_template.format(
1058
+ system_role=st.session_state['system_role'],
1059
+ classification_type=classification_type,
1060
+ domain=domain,
1061
+ examples="\n".join(examples_to_classify),
1062
+ labels=", ".join(labels),
1063
+ user_prompt=user_prompt,
1064
+ few_shot_examples=formatted_few_shot
1065
+ )
1066
+
1067
+ # Step 2: Store the system_prompt in st.session_state
1068
+ st.session_state['system_prompt'] = system_prompt
1069
+ #::contentReference[oaicite:0]{index=0}
1070
+ st.write("System Prompt:")
1071
+ #st.code(system_prompt)
1072
+ #st.code(st.session_state['system_prompt'])
1073
+ st.text_area("System Prompt", value=st.session_state['system_prompt'], height=300, max_chars=None, key=None, help=None, disabled=True)
1074
+
1075
+
1076
+
1077
+ if st.button("🏷️ Label Data"):
1078
+ if examples_to_classify:
1079
+ with st.spinner("Labeling data..."):
1080
+ #Generate the system prompt based on classification type
1081
+ if classification_type == "Named Entity Recognition (NER)":
1082
+ system_prompt = label_prompt_template.format(
1083
+ system_role=st.session_state['system_role'],
1084
+ labels=", ".join(labels),
1085
+ domain = domain,
1086
+ few_shot_examples=few_shot_text,
1087
+ examples=examples_text,
1088
+ user_prompt=user_prompt
1089
+ #new
1090
+ #'Use few-shot example?': 'Yes' if use_few_shot else 'No',
1091
+ )
1092
+ # if classification_type == "Named Entity Recognition (NER)":
1093
+ # # Step 1: Split the full response by example
1094
+ # raw_outputs = [block.strip() for block in response.strip().split("Entity types") if block.strip()]
1095
+ # inputs = [ex.strip() for ex in examples_to_classify]
1096
+
1097
+ # # Step 2: Match inputs with NER output blocks
1098
+ # labeled_examples = []
1099
+ # for i, (text, output_block) in enumerate(zip(inputs, raw_outputs)):
1100
+ # labeled_examples.append({
1101
+ # 'text': text,
1102
+ # 'entities': f"Entity types\n{output_block.strip()}",
1103
+ # 'system_prompt': st.session_state.system_prompt,
1104
+ # 'system_role': st.session_state.system_role,
1105
+ # 'task_type': 'Named Entity Recognition (NER)',
1106
+ # 'Use few-shot example?': 'Yes' if use_few_shot else 'No',
1107
+ # })
1108
+
1109
+ # if classification_type == "Named Entity Recognition (NER)":
1110
+ # # Step 1: Split the full response by example
1111
+ # raw_outputs = [block.strip() for block in response.strip().split("Entity types") if block.strip()]
1112
+ # inputs = [ex.strip() for ex in examples_to_classify]
1113
+
1114
+ # # Step 2: Match inputs with NER output blocks
1115
+ # labeled_examples = []
1116
+ # for i, (text, output_block) in enumerate(zip(inputs, raw_outputs)):
1117
+ # labeled_examples.append({
1118
+ # 'text': text,
1119
+ # 'entities': f"Entity types\n{output_block.strip()}",
1120
+ # 'system_prompt': st.session_state.system_prompt,
1121
+ # 'system_role': st.session_state.system_role,
1122
+ # 'task_type': 'Named Entity Recognition (NER)',
1123
+ # 'Use few-shot example?': 'Yes' if use_few_shot else 'No',
1124
+ # })
1125
+
1126
+
1127
+ # import re
1128
+
1129
+ # if classification_type == "Named Entity Recognition (NER)":
1130
+ # # Use regex to split on "Entity types" while keeping it attached to each block
1131
+ # blocks = re.split(r"(Entity types)", response.strip())
1132
+
1133
+ # # Recombine 'Entity types' with each block after splitting
1134
+ # raw_outputs = [
1135
+ # (blocks[i] + blocks[i+1]).strip()
1136
+ # for i in range(1, len(blocks) - 1, 2)
1137
+ # ]
1138
+
1139
+ # inputs = [ex.strip() for ex in examples_to_classify]
1140
+
1141
+ # labeled_examples = []
1142
+ # for i, (text, output_block) in enumerate(zip(inputs, raw_outputs)):
1143
+ # labeled_examples.append({
1144
+ # 'text': text,
1145
+ # 'entities': output_block,
1146
+ # 'system_prompt': st.session_state.system_prompt,
1147
+ # 'system_role': st.session_state.system_role,
1148
+ # 'task_type': 'Named Entity Recognition (NER)',
1149
+ # 'Use few-shot example?': 'Yes' if use_few_shot else 'No',
1150
+ # })
1151
+
1152
+
1153
+ else:
1154
+ system_prompt = label_prompt_template.format(
1155
+ classification_type=classification_type,
1156
+ system_role=st.session_state['system_role'],
1157
+ domain = domain,
1158
+ labels=", ".join(labels),
1159
+ few_shot_examples=few_shot_text,
1160
+ examples=examples_text,
1161
+ user_prompt=user_prompt
1162
+ )
1163
+ try:
1164
+ stream = client.chat.completions.create(
1165
+ model=selected_model,
1166
+ messages=[{"role": "system", "content": system_prompt}],
1167
+ temperature=temperature,
1168
+ stream=True,
1169
+ max_tokens=20000,
1170
+ top_p = 0.9,
1171
+
1172
+ )
1173
+ #new 24 March
1174
+ # Append user message
1175
+ st.session_state.messages.append({"role": "user", "content": system_prompt})
1176
+ #################
1177
+ response = st.write_stream(stream)
1178
+ st.session_state.messages.append({"role": "assistant", "content": response})
1179
+ # Display the labeled examples
1180
+ # # Optional: If you want to add it as a chat-style message log
1181
+ # preview_str = st.session_state.labeled_preview.to_markdown(index=False)
1182
+ # st.session_state.messages.append({"role": "assistant", "content": f"Here is a preview of the labeled examples:\n\n{preview_str}"})
1183
+
1184
+
1185
+ # # Stream response and append assistant message
1186
+ # #14/4/2024
1187
+ # response = st.write_stream(stream)
1188
+ # st.session_state.messages.append({"role": "assistant", "content": response})
1189
+
1190
+ # Initialize session state variables if they don't exist
1191
+ if 'system_prompt' not in st.session_state:
1192
+ st.session_state.system_prompt = system_prompt
1193
+
1194
+ if 'response' not in st.session_state:
1195
+ st.session_state.response = response
1196
+
1197
+ if 'generated_examples' not in st.session_state:
1198
+ st.session_state.generated_examples = []
1199
+
1200
+ if 'generated_examples_csv' not in st.session_state:
1201
+ st.session_state.generated_examples_csv = None
1202
+
1203
+ if 'generated_examples_json' not in st.session_state:
1204
+ st.session_state.generated_examples_json = None
1205
+
1206
+
1207
+
1208
+
1209
+ # Save labeled examples to CSV
1210
+ #new 14/4/2025
1211
+ labeled_examples = []
1212
+ # if classification_type == "Named Entity Recognition (NER)":
1213
+ # labeled_examples = []
1214
+ # for line in response.split('\n'):
1215
+ # if line.strip():
1216
+ # parts = line.rsplit('Entities:', 1)
1217
+ # if len(parts) == 2:
1218
+ # text = parts[0].strip()
1219
+ # entities = parts[1].strip()
1220
+ # if text and entities:
1221
+ # labeled_examples.append({
1222
+ # 'text': text,
1223
+ # 'entities': entities,
1224
+ # 'system_prompt': st.session_state.system_prompt,
1225
+ # 'system_role': st.session_state.system_role,
1226
+ # 'task_type': 'Named Entity Recognition (NER)',
1227
+ # 'Use few-shot example?': 'Yes' if use_few_shot else 'No',
1228
+ # })
1229
+
1230
+ #new 22/4/2025
1231
+ if classification_type == "Named Entity Recognition (NER)":
1232
+ labeled_examples = [{
1233
+ 'ner_output': response.strip(),
1234
+ 'system_prompt': st.session_state.system_prompt,
1235
+ 'system_role': st.session_state.system_role,
1236
+ 'task_type': 'Named Entity Recognition (NER)',
1237
+ 'Use few-shot example?': 'Yes' if use_few_shot else 'No',
1238
+ }]
1239
+
1240
+ ######
1241
+
1242
+
1243
+ else:
1244
+ labeled_examples = []
1245
+ for line in response.split('\n'):
1246
+ if line.strip():
1247
+ parts = line.rsplit('Label:', 1)
1248
+ if len(parts) == 2:
1249
+ text = parts[0].strip()
1250
+ label = parts[1].strip()
1251
+ if text and label:
1252
+ labeled_examples.append({
1253
+ 'text': text,
1254
+ 'label': label,
1255
+ 'system_prompt': st.session_state.system_prompt,
1256
+ 'system_role': st.session_state.system_role,
1257
+ 'task_type': 'Data Labeling',
1258
+ 'Use few-shot example?': 'Yes' if use_few_shot else 'No',
1259
+ })
1260
+ # Save and provide download options
1261
+ if labeled_examples:
1262
+ # Update session state
1263
+ st.session_state.labeled_examples = labeled_examples
1264
+
1265
+ # Convert to CSV and JSON
1266
+ df = pd.DataFrame(labeled_examples)
1267
+ #new 22/4/2025
1268
+ # CSV
1269
+ st.session_state.labeled_examples_csv = df.to_csv(index=False).encode('utf-8')
1270
+
1271
+ # JSON
1272
+ st.session_state.labeled_examples_json = json.dumps({
1273
+ "metadata": {
1274
+ "domain": domain,
1275
+ "labels": labels,
1276
+ "used_few_shot": use_few_shot,
1277
+ "task_type": "Named Entity Recognition (NER)",
1278
+ "timestamp": datetime.now().isoformat()
1279
+ },
1280
+ "examples": labeled_examples
1281
+ }, indent=2).encode('utf-8')
1282
+
1283
+ ############
1284
+ # CSV
1285
+ # st.session_state.labeled_examples_csv = df.to_csv(index=False).encode('utf-8')
1286
+
1287
+ # # JSON
1288
+ # st.session_state.labeled_examples_json = json.dumps({
1289
+ # "metadata": {
1290
+ # "domain": domain,
1291
+ # "labels": labels,
1292
+ # "used_few_shot": use_few_shot,
1293
+ # "task_type": "Named Entity Recognition (NER)",
1294
+ # "timestamp": datetime.now().isoformat()
1295
+ # },
1296
+ # "examples": labeled_examples
1297
+ # }, indent=2).encode('utf-8')
1298
+
1299
+ ########
1300
+ # st.session_state.labeled_examples_csv = df.to_csv(index=False).encode('utf-8')
1301
+ # st.session_state.labeled_examples_json = json.dumps(labeled_examples, indent=2).encode('utf-8')
1302
+
1303
+ # Download buttons
1304
+ st.download_button(
1305
+ "📥 Download Labeled Examples (CSV)",
1306
+ st.session_state.labeled_examples_csv,
1307
+ "labeled_examples.csv",
1308
+ "text/csv",
1309
+ key='download-labeled-csv'
1310
+ )
1311
+
1312
+ st.markdown("""
1313
+ <div style='text-align: left; margin:15px 0; font-weight: 600; color: #666;'>. . . . . . or</div>
1314
+ """, unsafe_allow_html=True)
1315
+
1316
+ st.download_button(
1317
+ "📥 Download Labeled Examples (JSON)",
1318
+ st.session_state.labeled_examples_json,
1319
+ "labeled_examples.json",
1320
+ "application/json",
1321
+ key='download-labeled-json'
1322
+ )
1323
+ # Display the labeled examples
1324
+ st.markdown("##### 📋 Labeled Examples Preview")
1325
+ st.dataframe(df, use_container_width=True)
1326
+ # Display section
1327
+ #st.markdown("### 📋 Labeled Examples Preview")
1328
+ #st.dataframe(st.session_state.labeled_preview, use_container_width=True)
1329
+
1330
+
1331
+
1332
+ # if labeled_examples:
1333
+ # df = pd.DataFrame(labeled_examples)
1334
+ # csv = df.to_csv(index=False).encode('utf-8')
1335
+ # st.download_button(
1336
+ # "📥 Download Labeled Examples",
1337
+ # csv,
1338
+ # "labeled_examples.csv",
1339
+ # "text/csv",
1340
+ # key='download-labeled-csv'
1341
+ # )
1342
+ # # Add space and center the "or"
1343
+ # st.markdown("""
1344
+ # <div style='text-align: left; margin:15px 0; font-weight: 600; color: #666;'>. . . . . . or</div>
1345
+ # """, unsafe_allow_html=True)
1346
+
1347
+ # if labeled_examples:
1348
+ # df = pd.DataFrame(labeled_examples)
1349
+ # csv = df.to_csv(index=False).encode('utf-8')
1350
+ # st.download_button(
1351
+ # "📥 Download Labeled Examples",
1352
+ # csv,
1353
+ # "labeled_examples.json",
1354
+ # "text/json",
1355
+ # key='download-labeled-JSON'
1356
+ # )
1357
+
1358
+ # Add follow-up interaction options
1359
+ #st.markdown("---")
1360
+ #follow_up = st.radio(
1361
+ #"What would you like to do next?",
1362
+ #["Label more data", "Data Generation"],
1363
+ # key="labeling_follow_up"
1364
+ # )
1365
+
1366
+ if st.button("Continue"):
1367
+ if follow_up == "Label more data":
1368
+ st.session_state.examples_to_classify = []
1369
+ st.experimental_rerun()
1370
+ elif follow_up == "Data Generation":
1371
+ st.session_state.task_choice = "Data Labeling"
1372
+ st.experimental_rerun()
1373
+
1374
+ except Exception as e:
1375
+ st.error("An error occurred during labeling.")
1376
+ st.error(f"Details: {e}")
1377
+ else:
1378
+ st.warning("Please enter at least one example to classify.")
1379
+
1380
+ #st.session_state.messages.append({"role": "assistant", "content": response})
1381
+
1382
+
1383
+
1384
+
1385
+ # Footer
1386
+ st.markdown("---")
1387
+ st.markdown(
1388
+ """
1389
+ <div style='text-align: center'>
1390
+ <p>Made with ❤️ by Wedyan AlSakran 2025</p>
1391
+ </div>
1392
+ """,
1393
+ unsafe_allow_html=True
1394
+ )