WillHeld commited on
Commit
ef8a823
·
verified ·
1 Parent(s): eaf03fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -16
app.py CHANGED
@@ -3,13 +3,95 @@ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStream
3
  import gradio as gr
4
  from threading import Thread
5
  import os
 
 
 
 
 
 
 
6
  from gradio_modal import Modal
 
7
 
 
8
  checkpoint = "WillHeld/soft-raccoon"
9
  device = "cuda"
10
  tokenizer = AutoTokenizer.from_pretrained(checkpoint)
11
  model = AutoModelForCausalLM.from_pretrained(checkpoint).to(device)
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  @spaces.GPU(duration=120)
14
  def predict(message, history, temperature, top_p):
15
  history.append({"role": "user", "content": message})
@@ -27,7 +109,6 @@ def predict(message, history, temperature, top_p):
27
  "top_p": float(top_p),
28
  "do_sample": True,
29
  "streamer": streamer,
30
- "eos_token_id": 128009,
31
  }
32
 
33
  # Run generation in a separate thread
@@ -40,13 +121,30 @@ def predict(message, history, temperature, top_p):
40
  partial_text += new_text
41
  yield partial_text
42
 
43
- # Function to handle the report submission
44
- def submit_report(satisfaction, feedback_text):
45
- # In a real application, you might save this to a database or file
46
- print(f"Report submitted - Satisfaction: {satisfaction}, Feedback: {feedback_text}")
47
- return "Thank you for your feedback! Your report has been submitted."
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
 
49
  with gr.Blocks() as demo:
 
 
 
50
  with gr.Row():
51
  with gr.Column(scale=3):
52
  chatbot = gr.ChatInterface(
@@ -58,28 +156,43 @@ with gr.Blocks() as demo:
58
  type="messages"
59
  )
60
 
 
 
 
 
 
 
 
61
  with gr.Column(scale=1):
62
- report_button = gr.Button("File a Report", variant="primary")
63
 
64
  # Create the modal with feedback form components
65
  with Modal(visible=False) as feedback_modal:
66
  with gr.Column():
67
- gr.Markdown("## We value your feedback!")
68
- gr.Markdown("Please tell us about your experience with the model.")
 
 
 
 
 
 
 
 
69
 
70
  satisfaction = gr.Radio(
71
  ["Very satisfied", "Satisfied", "Neutral", "Unsatisfied", "Very unsatisfied"],
72
- label="How satisfied are you with the model's responses?",
73
  value="Neutral"
74
  )
75
 
76
  feedback_text = gr.Textbox(
77
  lines=5,
78
- label="Please provide any additional feedback or describe issues you encountered:",
79
- placeholder="Enter your detailed feedback here..."
80
  )
81
 
82
- submit_button = gr.Button("Submit Feedback", variant="primary")
83
  response_text = gr.Textbox(label="Status", interactive=False)
84
 
85
  # Connect the "File a Report" button to show the modal
@@ -89,11 +202,12 @@ with gr.Blocks() as demo:
89
  feedback_modal
90
  )
91
 
92
- # Connect the submit button to the submit_report function
93
  submit_button.click(
94
- submit_report,
95
- inputs=[satisfaction, feedback_text],
96
  outputs=response_text
97
  )
98
 
 
99
  demo.launch()
 
3
  import gradio as gr
4
  from threading import Thread
5
  import os
6
+ import json
7
+ import uuid
8
+ from datasets import Dataset
9
+ from huggingface_hub import HfApi, login
10
+ import huggingface_hub
11
+ import time
12
+
13
  from gradio_modal import Modal
14
+ import datasets
15
 
16
+ # Model setup
17
  checkpoint = "WillHeld/soft-raccoon"
18
  device = "cuda"
19
  tokenizer = AutoTokenizer.from_pretrained(checkpoint)
20
  model = AutoModelForCausalLM.from_pretrained(checkpoint).to(device)
21
 
22
+ # Constants for dataset
23
+ DATASET_REPO = "WillHeld/marin-feedback" # Replace with your username
24
+ DATASET_PATH = "./feedback_data" # Local path to store feedback
25
+ DATASET_FILENAME = "feedback.jsonl" # Filename for feedback data
26
+
27
+ # Ensure feedback directory exists
28
+ os.makedirs(DATASET_PATH, exist_ok=True)
29
+
30
+ # Feedback storage functions
31
+ def save_feedback_locally(conversation, satisfaction, feedback_text):
32
+ """Save feedback to a local JSONL file"""
33
+ # Create a unique ID for this feedback entry
34
+ feedback_id = str(uuid.uuid4())
35
+
36
+ # Create a timestamp
37
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
38
+
39
+ # Prepare the feedback data
40
+ feedback_data = {
41
+ "id": feedback_id,
42
+ "timestamp": timestamp,
43
+ "conversation": conversation,
44
+ "satisfaction": satisfaction,
45
+ "feedback": feedback_text
46
+ }
47
+
48
+ # Save to local file
49
+ feedback_file = os.path.join(DATASET_PATH, DATASET_FILENAME)
50
+ with open(feedback_file, "a") as f:
51
+ f.write(json.dumps(feedback_data) + "\n")
52
+
53
+ return feedback_id
54
+
55
+ def push_feedback_to_hub(hf_token=None):
56
+ """Push the local feedback data to HuggingFace as a dataset"""
57
+ # Check if we have a token
58
+ if hf_token is None:
59
+ # Try to get token from environment variable
60
+ hf_token = os.environ.get("HF_TOKEN")
61
+ if hf_token is None:
62
+ print("No HuggingFace token provided. Cannot push to Hub.")
63
+ return False
64
+
65
+ try:
66
+ # Login to HuggingFace
67
+ login(token=hf_token)
68
+
69
+ # Check if we have data to push
70
+ feedback_file = os.path.join(DATASET_PATH, DATASET_FILENAME)
71
+ if not os.path.exists(feedback_file):
72
+ print("No feedback data to push.")
73
+ return False
74
+
75
+ # Load data from the JSONL file
76
+ with open(feedback_file, "r") as f:
77
+ feedback_data = [json.loads(line) for line in f]
78
+
79
+ # Create a dataset from the feedback data
80
+ dataset = Dataset.from_list(feedback_data)
81
+
82
+ # Push to Hub
83
+ dataset.push_to_hub(
84
+ DATASET_REPO,
85
+ private=True # Set to False if you want the dataset to be public
86
+ )
87
+
88
+ print(f"Feedback data pushed to {DATASET_REPO} successfully.")
89
+ return True
90
+
91
+ except Exception as e:
92
+ print(f"Error pushing feedback data to Hub: {e}")
93
+ return False
94
+
95
  @spaces.GPU(duration=120)
96
  def predict(message, history, temperature, top_p):
97
  history.append({"role": "user", "content": message})
 
109
  "top_p": float(top_p),
110
  "do_sample": True,
111
  "streamer": streamer,
 
112
  }
113
 
114
  # Run generation in a separate thread
 
121
  partial_text += new_text
122
  yield partial_text
123
 
124
+ # Function to handle the research feedback submission
125
+ def submit_research_feedback(conversation_history, satisfaction, feedback_text, hf_token=None):
126
+ """Save user feedback both locally and to HuggingFace Hub"""
127
+ # Save locally first
128
+ feedback_id = save_feedback_locally(conversation_history, satisfaction, feedback_text)
129
+
130
+ # Get token from environment variable
131
+ env_token = os.environ.get("HF_TOKEN")
132
+
133
+ # Use environment token, ignoring any passed token
134
+ push_success = push_feedback_to_hub(env_token)
135
+
136
+ if push_success:
137
+ status_msg = "Thank you for your valuable feedback! Your insights have been saved to the dataset."
138
+ else:
139
+ status_msg = "Thank you for your feedback! It has been saved locally, but couldn't be pushed to the dataset. Please check server logs."
140
+
141
+ return status_msg
142
 
143
+ # Create the Gradio interface
144
  with gr.Blocks() as demo:
145
+ # Store conversation history
146
+ conversation_state = gr.State([])
147
+
148
  with gr.Row():
149
  with gr.Column(scale=3):
150
  chatbot = gr.ChatInterface(
 
156
  type="messages"
157
  )
158
 
159
+ # Update conversation_state with each new message
160
+ chatbot.submit_btn.click(
161
+ lambda history: history,
162
+ inputs=[chatbot.chat_history],
163
+ outputs=[conversation_state]
164
+ )
165
+
166
  with gr.Column(scale=1):
167
+ report_button = gr.Button("Share Feedback", variant="primary")
168
 
169
  # Create the modal with feedback form components
170
  with Modal(visible=False) as feedback_modal:
171
  with gr.Column():
172
+ gr.Markdown("## Research Preview Feedback")
173
+ gr.Markdown("Thank you for testing our research model. Your feedback (positive or negative) helps us improve!")
174
+
175
+ # Optional: HF Token for pushing to Hub
176
+ hf_token_input = gr.Textbox(
177
+ label="HuggingFace Token (Optional)",
178
+ placeholder="Enter your HF token to push feedback to dataset",
179
+ type="password",
180
+ visible=True # Set to False in production if using environment variables
181
+ )
182
 
183
  satisfaction = gr.Radio(
184
  ["Very satisfied", "Satisfied", "Neutral", "Unsatisfied", "Very unsatisfied"],
185
+ label="How would you rate your experience with this research model?",
186
  value="Neutral"
187
  )
188
 
189
  feedback_text = gr.Textbox(
190
  lines=5,
191
+ label="Share your observations (strengths, weaknesses, suggestions):",
192
+ placeholder="We welcome both positive feedback and constructive criticism to help improve this research prototype..."
193
  )
194
 
195
+ submit_button = gr.Button("Submit Research Feedback", variant="primary")
196
  response_text = gr.Textbox(label="Status", interactive=False)
197
 
198
  # Connect the "File a Report" button to show the modal
 
202
  feedback_modal
203
  )
204
 
205
+ # Connect the submit button to the submit_research_feedback function
206
  submit_button.click(
207
+ submit_research_feedback,
208
+ inputs=[conversation_state, satisfaction, feedback_text, hf_token_input],
209
  outputs=response_text
210
  )
211
 
212
+ # Launch the demo
213
  demo.launch()