Wedyan2023 commited on
Commit
59f85b8
·
verified ·
1 Parent(s): 0217880

Create app6.py

Browse files
Files changed (1) hide show
  1. app6.py +190 -0
app6.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import streamlit as st
3
+ from openai import OpenAI
4
+ import os
5
+ from dotenv import load_dotenv
6
+ import random
7
+
8
+ os.environ["BROWSER_GATHERUSAGESTATS"] = "false"
9
+ load_dotenv()
10
+
11
+ # Initialize the client
12
+ client = OpenAI(
13
+ base_url="https://api-inference.huggingface.co/v1",
14
+ api_key=os.environ.get('GP2_2') # Add your Huggingface token here
15
+ )
16
+
17
+ # Supported models
18
+ model_links = {
19
+ "Meta-Llama-3-8B": "meta-llama/Meta-Llama-3-8B-Instruct"
20
+ }
21
+
22
+ # Reset conversation
23
+ def reset_conversation():
24
+ st.session_state.conversation = []
25
+ st.session_state.messages = []
26
+
27
+ # Define the available models
28
+ models = [key for key in model_links.keys()]
29
+
30
+ # Sidebar for model selection
31
+ selected_model = st.sidebar.selectbox("Select Model", models)
32
+ temp_values = st.sidebar.slider('Select a temperature value', 0.0, 1.0, 0.5)
33
+ st.sidebar.button('Reset Chat', on_click=reset_conversation)
34
+ st.sidebar.write(f"You're now chatting with **{selected_model}**")
35
+ st.sidebar.markdown("*Generated content may be inaccurate or false.*")
36
+
37
+ # Chat initialization
38
+ if "messages" not in st.session_state:
39
+ st.session_state.messages = []
40
+
41
+ for message in st.session_state.messages:
42
+ with st.chat_message(message["role"]):
43
+ st.markdown(message["content"])
44
+
45
+ # Main logic to choose between data generation and data labeling
46
+ task_choice = st.selectbox("Choose Task", ["Data Generation", "Data Labeling"])
47
+
48
+ if task_choice == "Data Generation":
49
+ classification_type = st.selectbox(
50
+ "Choose Classification Type",
51
+ ["Sentiment Analysis", "Binary Classification", "Multi-Class Classification"]
52
+ )
53
+
54
+ if classification_type == "Sentiment Analysis":
55
+ st.write("Sentiment Analysis: Positive, Negative, Neutral")
56
+ labels = ["Positive", "Negative", "Neutral"]
57
+ elif classification_type == "Binary Classification":
58
+ label_1 = st.text_input("Enter first class")
59
+ label_2 = st.text_input("Enter second class")
60
+ labels = [label_1, label_2]
61
+ elif classification_type == "Multi-Class Classification":
62
+ num_classes = st.slider("How many classes?", 3, 10, 3)
63
+ labels = [st.text_input(f"Class {i+1}") for i in range(num_classes)]
64
+
65
+ domain = st.selectbox("Choose Domain", ["Restaurant reviews", "E-commerce reviews", "Custom"])
66
+ if domain == "Custom":
67
+ domain = st.text_input("Specify custom domain")
68
+
69
+ min_words = st.number_input("Minimum words per example", min_value=10, max_value=90, value=10)
70
+ max_words = st.number_input("Maximum words per example", min_value=10, max_value=90, value=90)
71
+
72
+ few_shot = st.radio("Do you want to use few-shot examples?", ["Yes", "No"])
73
+ if few_shot == "Yes":
74
+ num_examples = st.slider("How many few-shot examples?", 1, 5, 1)
75
+ few_shot_examples = [
76
+ {"content": st.text_area(f"Example {i+1}"), "label": st.selectbox(f"Label for example {i+1}", labels)}
77
+ for i in range(num_examples)
78
+ ]
79
+ else:
80
+ few_shot_examples = []
81
+
82
+ num_to_generate = st.number_input("How many examples to generate?", min_value=1, max_value=100, value=10)
83
+ user_prompt = st.text_area("Enter your prompt to guide example generation", "")
84
+
85
+ # System prompt generation
86
+ system_prompt = f"You are a professional {classification_type.lower()} expert. Your role is to generate data for {domain}.\n\n"
87
+ if few_shot_examples:
88
+ system_prompt += "Use the following few-shot examples as a reference:\n"
89
+ for example in few_shot_examples:
90
+ system_prompt += f"Example: {example['content']} \n Label: {example['label']}\n"
91
+ system_prompt += f"Generate {num_to_generate} unique examples with diverse phrasing.\n"
92
+ system_prompt += f"Each example should have between {min_words} and {max_words} words.\n"
93
+ system_prompt += f"Use the labels specified: {', '.join(labels)}.\n"
94
+ if user_prompt:
95
+ system_prompt += f"Additional instructions: {user_prompt}\n"
96
+
97
+ st.write("System Prompt:")
98
+ st.code(system_prompt)
99
+
100
+ if st.button("Generate Examples"):
101
+ with st.spinner("Generating..."):
102
+ st.session_state.messages.append({"role": "system", "content": system_prompt})
103
+
104
+ try:
105
+ stream = client.chat.completions.create(
106
+ model=model_links[selected_model],
107
+ messages=[
108
+ {"role": m["role"], "content": m["content"]}
109
+ for m in st.session_state.messages
110
+ ],
111
+ temperature=temp_values,
112
+ stream=True,
113
+ max_tokens=3000,
114
+ )
115
+ response = st.write_stream(stream)
116
+ except Exception as e:
117
+ st.error("An error occurred during generation.")
118
+ st.error(f"Error details: {str(e)}")
119
+
120
+ st.session_state.messages.append({"role": "assistant", "content": response})
121
+
122
+ else: # Data Labeling Process
123
+ labeling_classification_type = st.selectbox(
124
+ "Choose Classification Type for Labeling",
125
+ ["Sentiment Analysis", "Binary Classification", "Multi-Class Classification"]
126
+ )
127
+
128
+ if labeling_classification_type == "Sentiment Analysis":
129
+ st.write("Sentiment Analysis: Positive, Negative, Neutral")
130
+ labeling_labels = ["Positive", "Negative", "Neutral"]
131
+ elif labeling_classification_type == "Binary Classification":
132
+ labeling_label_1 = st.text_input("Enter first class for labeling")
133
+ labeling_label_2 = st.text_input("Enter second class for labeling")
134
+ labeling_labels = [labeling_label_1, labeling_label_2]
135
+ elif labeling_classification_type == "Multi-Class Classification":
136
+ labeling_num_classes = st.slider("How many classes for labeling?", 3, 10, 3)
137
+ labeling_labels = [st.text_input(f"Labeling Class {i+1}") for i in range(labeling_num_classes)]
138
+
139
+ labeling_few_shot = st.radio("Do you want to add few-shot examples for labeling?", ["Yes", "No"])
140
+ if labeling_few_shot == "Yes":
141
+ labeling_num_examples = st.slider("How many few-shot examples for labeling?", 1, 5, 1)
142
+ labeling_few_shot_examples = [
143
+ {"content": st.text_area(f"Labeling Example {i+1}"),
144
+ "label": st.selectbox(f"Label for labeling example {i+1}", labeling_labels)}
145
+ for i in range(labeling_num_examples)
146
+ ]
147
+ else:
148
+ labeling_few_shot_examples = []
149
+
150
+ text_to_classify = st.text_area("Enter text to classify")
151
+
152
+ if st.button("Classify Text"):
153
+ if text_to_classify:
154
+ labeling_system_prompt = (
155
+ f"You are a professional {labeling_classification_type.lower()} expert. "
156
+ f"Classify the following text using these labels: {', '.join(labeling_labels)}.\n\n"
157
+ )
158
+ if labeling_few_shot_examples:
159
+ labeling_system_prompt += "Here are some example classifications:\n"
160
+ for example in labeling_few_shot_examples:
161
+ labeling_system_prompt += f"Review: {example['content']}\nLabel: {example['label']}\n\n"
162
+
163
+ labeling_system_prompt += (
164
+ f"Text to classify: {text_to_classify}\n"
165
+ f"Provide only the classification result in this format:\n"
166
+ f"'Review: [text provided] Label: [appropriate label]'\n"
167
+ )
168
+
169
+ with st.spinner("Classifying..."):
170
+ st.session_state.messages.append({"role": "system", "content": labeling_system_prompt})
171
+
172
+ try:
173
+ stream = client.chat.completions.create(
174
+ model=model_links[selected_model],
175
+ messages=[
176
+ {"role": m["role"], "content": m["content"]}
177
+ for m in st.session_state.messages
178
+ ],
179
+ temperature=temp_values,
180
+ stream=True,
181
+ max_tokens=1000,
182
+ )
183
+ response = st.write_stream(stream)
184
+ except Exception as e:
185
+ st.error("An error occurred during classification.")
186
+ st.error(f"Error details: {str(e)}")
187
+
188
+ st.session_state.messages.append({"role": "assistant", "content": response})
189
+ else:
190
+ st.warning("Please enter text to classify.")