Keeby-smilyai commited on
Commit
105bb74
Β·
verified Β·
1 Parent(s): 42cf83c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -71
app.py CHANGED
@@ -1,25 +1,21 @@
1
- # app.py β€” STABLE VERSION UPDATED WITH USERNAME/PASSWORD
2
  import gradio as gr
3
- # --- MODIFIED: Updated backend imports ---
4
  from backend import (
5
  login_user,
6
  signup_user,
7
  get_user_runs,
8
  get_run_logs,
9
  queue_training_run,
10
- start_training_if_free,
11
  publish_run_to_hub,
12
  run_inference
13
  )
14
  from utils import ARCH_ANALOGIES, get_auto_hyperparams
15
 
16
- # ------------------------------ STATE (MODIFIED) ------------------------------
17
- # HF Token is no longer stored globally. Username is stored instead.
18
  user_state = {"user_id": None, "username": "", "arch_config": {}}
19
 
20
  # ------------------------------ BACKEND WRAPPERS (UI LOGIC) ------------------------------
21
 
22
- # --- NEW: Login and Signup Actions ---
23
  def login_action(username, password):
24
  user_id, msg = login_user(username, password)
25
  if user_id:
@@ -27,32 +23,30 @@ def login_action(username, password):
27
  user_state["username"] = username
28
  runs_list = page_processes()
29
  return gr.update(visible=False), gr.update(visible=True), msg, runs_list
30
- else:
31
- return gr.update(), gr.update(), msg, ""
32
 
33
  def signup_action(username, password):
34
  user_id, msg = signup_user(username, password)
35
  if user_id:
36
- # On success, go back to the login page with a success message
37
  return gr.update(visible=False), gr.update(visible=True), msg
38
- else:
39
- # On failure, show an error message on the signup page
40
- return gr.update(), gr.update(), msg
41
 
42
- # --- (The following functions are from the old stable version, unchanged) ---
43
  def page_processes():
44
  if not user_state.get("user_id"): return "Login required."
45
  runs = get_user_runs(user_state["user_id"])
46
- run_list = "\n".join([f"🍳 Run #{r[0]} | {r[1].upper()} x{r[2]} layers | Status: {r[3]}" for r in runs]) or "No runs yet. Start cooking!"
47
  return run_list
48
 
49
  def load_run_logs(run_id_str):
50
  try:
51
  run_id = int(run_id_str)
52
- logs, status = get_run_logs(run_id)
 
 
 
53
  return f"Status: {status}\n\n{logs}"
54
  except:
55
- return "Invalid or empty Run ID."
56
 
57
  def page_architecture_next(arch_type, num_layers):
58
  analogy = ARCH_ANALOGIES.get(arch_type, "")
@@ -63,52 +57,34 @@ def page_architecture_next(arch_type, num_layers):
63
 
64
  def page_hyperparams_next(lr, epochs, batch_size):
65
  config = user_state["arch_config"]
66
- final_config = {
67
- "arch_type": config["arch_type"],
68
- "num_layers": config["num_layers"],
69
- "learning_rate": float(lr) if lr else config["auto_config"]["learning_rate"],
70
- "epochs": int(epochs) if epochs else config["auto_config"]["epochs"],
71
- "batch_size": int(batch_size) if batch_size else config["auto_config"]["batch_size"],
72
- }
73
  queue_training_run(user_state["user_id"], final_config)
74
- # The new parallel backend handles calling start_training_if_free() automatically
75
- refreshed_runs = page_processes()
76
- return gr.update(visible=False), gr.update(visible=True), refreshed_runs
77
 
78
  def get_completed_runs():
79
  all_runs = get_user_runs(user_state["user_id"])
80
  return [r for r in all_runs if r[3] == 'completed']
81
 
82
- def go_to_inference_page():
83
  completed_runs = get_completed_runs()
84
  if not completed_runs:
85
- gr.Warning("You have no completed models to test! Finish a training run first.")
86
  return gr.update(), gr.update(), gr.update(choices=[])
87
  choices = [(f"Run #{r[0]}: {r[1].upper()} x{r[2]}L", r[0]) for r in completed_runs]
88
- return gr.update(visible=False), gr.update(visible=True), gr.update(choices=choices, value=choices[0][1])
89
-
90
- def go_to_publish_page():
91
- completed_runs = get_completed_runs()
92
- if not completed_runs:
93
- gr.Warning("You have no completed models to publish! Finish a training run first.")
94
- return gr.update(), gr.update(), gr.update(choices=[]), gr.update()
95
- choices = [(f"Run #{r[0]}: {r[1].upper()} x{r[2]}L", r[0]) for r in completed_runs]
96
- return gr.update(visible=False), gr.update(visible=True), gr.update(choices=choices, value=choices[0][1]), ""
97
 
98
  def inference_action(run_id, prompt):
99
- if not run_id: return "Error: Please select a model from the dropdown."
100
  try: return run_inference(run_id, prompt)
101
  except Exception as e: return f"Error: {str(e)}"
102
 
103
- # --- MODIFIED: Publish action now takes the HF token from the UI ---
104
  def publish_action(run_id, hf_token, description):
105
  if not run_id: return "Error: Please select a model to publish."
106
- if not hf_token.strip(): return "Error: Hugging Face Token is required to publish."
107
  try:
108
- run_details = next((r for r in get_completed_runs() if r[0] == run_id), None)
109
- repo_name = f"llm-kitchen-{run_details[1]}-{run_details[2]}L-run{run_id}" if run_details else f"llm-kitchen-run-{run_id}"
110
- url = publish_run_to_hub(run_id, hf_token, repo_name, description.strip())
111
- return f"πŸš€ Published! View at: {url}"
112
  except Exception as e:
113
  return f"Publish failed: {str(e)}"
114
 
@@ -118,7 +94,6 @@ with gr.Blocks(title="LLM Kitchen 🍳", theme=gr.themes.Soft()) as demo:
118
  gr.Markdown("# 🍳 Welcome to LLM Kitchen")
119
  gr.Markdown("### Cook your own language model β€” from scratch!")
120
 
121
- # --- NEW: SIGNUP PAGE ---
122
  with gr.Group(visible=False) as page_signup_ui:
123
  gr.Markdown("### πŸ“ Create a New Account")
124
  signup_user_input = gr.Textbox(label="Username")
@@ -127,7 +102,6 @@ with gr.Blocks(title="LLM Kitchen 🍳", theme=gr.themes.Soft()) as demo:
127
  signup_msg = gr.Markdown()
128
  go_to_login_btn = gr.Button("Already have an account? Log In")
129
 
130
- # --- NEW: LOGIN PAGE (Replaces old HF Token login) ---
131
  with gr.Group() as page_login_ui:
132
  gr.Markdown("### πŸ” Login to the Kitchen")
133
  login_user_input = gr.Textbox(label="Username")
@@ -136,41 +110,36 @@ with gr.Blocks(title="LLM Kitchen 🍳", theme=gr.themes.Soft()) as demo:
136
  login_msg = gr.Markdown()
137
  go_to_signup_btn = gr.Button("Don't have an account? Sign Up")
138
 
139
- # ---- PAGE 2: PROCESSES (Unchanged) ----
140
  with gr.Group(visible=False) as page_processes_ui:
141
- gr.Markdown("### πŸ§‘β€πŸ³ Your Processes")
142
  with gr.Row():
143
- refresh_btn = gr.Button("πŸ”„ Refresh List")
144
- inference_btn = gr.Button("πŸ§ͺ Go to Inference Kitchen")
145
- publish_btn = gr.Button("πŸš€ Go to Publishing Bay")
146
  runs_display = gr.Textbox(label="Your Training Runs", lines=8, interactive=False)
147
  with gr.Accordion("View Raw Logs", open=False):
148
- run_id_input = gr.Textbox(label="Enter a Run ID to view its logs")
149
  view_logs_btn = gr.Button("View Logs")
150
  logs_display = gr.Textbox(label="Training Logs", lines=10, interactive=False)
151
  new_run_btn = gr.Button("βž• Start New Process", variant="primary")
152
 
153
- # ---- PAGE 3: INFERENCE KITCHEN (Unchanged) ----
154
  with gr.Group(visible=False) as page_inference_ui:
155
  gr.Markdown("### πŸ§ͺ Inference Kitchen")
156
- inf_run_id_dropdown = gr.Dropdown(label="Select a Completed Model to Use")
157
- prompt_input = gr.Textbox(label="Your Prompt", lines=3, placeholder="e.g., Explain gravity like I'm five...")
158
  infer_btn = gr.Button("Generate Answer")
159
  output_text = gr.Textbox(label="Model's Answer", lines=5, interactive=False)
160
  back_from_inf = gr.Button("⬅️ Back to Processes")
161
 
162
- # ---- PAGE 4: PUBLISHING BAY (MODIFIED) ----
163
  with gr.Group(visible=False) as page_publish_ui:
164
  gr.Markdown("### πŸš€ Publishing Bay")
165
  pub_run_id_dropdown = gr.Dropdown(label="Select a Completed Model to Publish")
166
- # --- NEW: HF Token input field ---
167
- pub_hf_token_input = gr.Textbox(label="Your Hugging Face Token (with write permissions)", type="password", placeholder="hf_...")
168
- pub_description_input = gr.Textbox(label="Model Card Description", lines=4, placeholder="Write a short description for your model card...")
169
  publish_now_btn = gr.Button("Publish to Hugging Face Hub", variant="primary")
170
  publish_status = gr.Markdown()
171
  back_from_pub = gr.Button("⬅️ Back to Processes")
172
 
173
- # ---- PAGE 5 & 6: ARCHITECTURE & HYPERPARAMETERS (Unchanged) ----
174
  with gr.Group(visible=False) as page_arch_ui:
175
  gr.Markdown("### πŸ—οΈ Step 2: Choose Your Architecture")
176
  arch_dropdown = gr.Dropdown(["cnn", "rnn", "transformer"], label="Architecture Type")
@@ -178,34 +147,31 @@ with gr.Blocks(title="LLM Kitchen 🍳", theme=gr.themes.Soft()) as demo:
178
  arch_next_btn = gr.Button("Next β†’ Hyperparameters")
179
  arch_analogy = gr.Markdown()
180
  auto_suggestion = gr.Markdown()
 
181
  with gr.Group(visible=False) as page_hyper_ui:
182
- gr.Markdown("### πŸ§‚ Step 3: Season Your Model (Hyperparameters)")
183
- gr.Markdown("Use Auto-Seasoningβ„’ (pre-filled) or customize manually")
184
  lr_input = gr.Number(label="Learning Rate")
185
  epochs_input = gr.Number(label="Epochs", precision=0)
186
  batch_input = gr.Number(label="Batch Size", precision=0)
187
  hyper_next_btn = gr.Button("Start Cooking! 🍲")
188
 
189
- # ------------------------------ EVENTS (MODIFIED) ------------------------------
190
-
191
- # --- NEW: Auth flow events ---
192
  go_to_signup_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[page_login_ui, page_signup_ui])
193
  go_to_login_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[page_signup_ui, page_login_ui])
194
  login_btn.click(login_action, inputs=[login_user_input, login_pass_input], outputs=[page_login_ui, page_processes_ui, login_msg, runs_display])
195
  signup_btn.click(signup_action, inputs=[signup_user_input, signup_pass_input], outputs=[page_signup_ui, page_login_ui, signup_msg])
196
-
197
- # --- Old events, mostly unchanged ---
198
  refresh_btn.click(page_processes, outputs=runs_display)
199
  view_logs_btn.click(load_run_logs, inputs=run_id_input, outputs=logs_display)
200
- new_run_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True), "", ""), outputs=[page_processes_ui, page_arch_ui, arch_analogy, auto_suggestion])
201
  arch_next_btn.click(page_architecture_next, inputs=[arch_dropdown, layers_slider], outputs=[page_arch_ui, page_hyper_ui, arch_analogy, auto_suggestion, lr_input, epochs_input, batch_input])
202
  hyper_next_btn.click(page_hyperparams_next, inputs=[lr_input, epochs_input, batch_input], outputs=[page_hyper_ui, page_processes_ui, runs_display])
203
- inference_btn.click(go_to_inference_page, outputs=[page_processes_ui, page_inference_ui, inf_run_id_dropdown])
 
204
  infer_btn.click(inference_action, inputs=[inf_run_id_dropdown, prompt_input], outputs=output_text)
205
  back_from_inf.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[page_inference_ui, page_processes_ui])
206
 
207
- # --- MODIFIED: Publish event now includes the HF token input ---
208
- publish_btn.click(go_to_publish_page, outputs=[page_processes_ui, page_publish_ui, pub_run_id_dropdown, publish_status])
209
  publish_now_btn.click(publish_action, inputs=[pub_run_id_dropdown, pub_hf_token_input, pub_description_input], outputs=publish_status)
210
  back_from_pub.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[page_publish_ui, page_processes_ui])
211
 
 
1
+ # app.py β€” FINAL VERSION
2
  import gradio as gr
 
3
  from backend import (
4
  login_user,
5
  signup_user,
6
  get_user_runs,
7
  get_run_logs,
8
  queue_training_run,
 
9
  publish_run_to_hub,
10
  run_inference
11
  )
12
  from utils import ARCH_ANALOGIES, get_auto_hyperparams
13
 
14
+ # ------------------------------ STATE ------------------------------
 
15
  user_state = {"user_id": None, "username": "", "arch_config": {}}
16
 
17
  # ------------------------------ BACKEND WRAPPERS (UI LOGIC) ------------------------------
18
 
 
19
  def login_action(username, password):
20
  user_id, msg = login_user(username, password)
21
  if user_id:
 
23
  user_state["username"] = username
24
  runs_list = page_processes()
25
  return gr.update(visible=False), gr.update(visible=True), msg, runs_list
26
+ return gr.update(), gr.update(), msg, ""
 
27
 
28
  def signup_action(username, password):
29
  user_id, msg = signup_user(username, password)
30
  if user_id:
 
31
  return gr.update(visible=False), gr.update(visible=True), msg
32
+ return gr.update(), gr.update(), msg
 
 
33
 
 
34
  def page_processes():
35
  if not user_state.get("user_id"): return "Login required."
36
  runs = get_user_runs(user_state["user_id"])
37
+ run_list = "\n".join([f"🍳 Run #{r[0]} | {r[1].upper()} x{r[2]}L | Status: {r[3]}" for r in runs]) or "No runs yet."
38
  return run_list
39
 
40
  def load_run_logs(run_id_str):
41
  try:
42
  run_id = int(run_id_str)
43
+ user_id = user_state["user_id"]
44
+ logs, status = get_run_logs(user_id, run_id)
45
+ if status == "unknown":
46
+ return "Error: Run not found or you do not have permission to view it."
47
  return f"Status: {status}\n\n{logs}"
48
  except:
49
+ return "Invalid Run ID format. Please enter a number."
50
 
51
  def page_architecture_next(arch_type, num_layers):
52
  analogy = ARCH_ANALOGIES.get(arch_type, "")
 
57
 
58
  def page_hyperparams_next(lr, epochs, batch_size):
59
  config = user_state["arch_config"]
60
+ final_config = {"arch_type": config["arch_type"], "num_layers": config["num_layers"], "learning_rate": float(lr) if lr else config["auto_config"]["learning_rate"], "epochs": int(epochs) if epochs else config["auto_config"]["epochs"], "batch_size": int(batch_size) if batch_size else config["auto_config"]["batch_size"]}
 
 
 
 
 
 
61
  queue_training_run(user_state["user_id"], final_config)
62
+ return gr.update(visible=False), gr.update(visible=True), page_processes()
 
 
63
 
64
  def get_completed_runs():
65
  all_runs = get_user_runs(user_state["user_id"])
66
  return [r for r in all_runs if r[3] == 'completed']
67
 
68
+ def go_to_page_with_run_list(page_to_show):
69
  completed_runs = get_completed_runs()
70
  if not completed_runs:
71
+ gr.Warning("You have no completed models! Finish a training run first.")
72
  return gr.update(), gr.update(), gr.update(choices=[])
73
  choices = [(f"Run #{r[0]}: {r[1].upper()} x{r[2]}L", r[0]) for r in completed_runs]
74
+ return gr.update(visible=False), page_to_show, gr.update(choices=choices, value=choices[0][1])
 
 
 
 
 
 
 
 
75
 
76
  def inference_action(run_id, prompt):
77
+ if not run_id: return "Error: Please select a model."
78
  try: return run_inference(run_id, prompt)
79
  except Exception as e: return f"Error: {str(e)}"
80
 
 
81
  def publish_action(run_id, hf_token, description):
82
  if not run_id: return "Error: Please select a model to publish."
83
+ if not hf_token: return "Error: Hugging Face Token is required."
84
  try:
85
+ run_info = next((r for r in get_completed_runs() if r[0] == run_id), None)
86
+ repo_name = f"llm-kitchen-{run_info[1]}-{run_info[2]}L-run{run_id}" if run_info else f"llm-kitchen-run-{run_id}"
87
+ return publish_run_to_hub(run_id, hf_token, repo_name, description.strip())
 
88
  except Exception as e:
89
  return f"Publish failed: {str(e)}"
90
 
 
94
  gr.Markdown("# 🍳 Welcome to LLM Kitchen")
95
  gr.Markdown("### Cook your own language model β€” from scratch!")
96
 
 
97
  with gr.Group(visible=False) as page_signup_ui:
98
  gr.Markdown("### πŸ“ Create a New Account")
99
  signup_user_input = gr.Textbox(label="Username")
 
102
  signup_msg = gr.Markdown()
103
  go_to_login_btn = gr.Button("Already have an account? Log In")
104
 
 
105
  with gr.Group() as page_login_ui:
106
  gr.Markdown("### πŸ” Login to the Kitchen")
107
  login_user_input = gr.Textbox(label="Username")
 
110
  login_msg = gr.Markdown()
111
  go_to_signup_btn = gr.Button("Don't have an account? Sign Up")
112
 
 
113
  with gr.Group(visible=False) as page_processes_ui:
114
+ gr.Markdown(f"### πŸ§‘β€πŸ³ Your Processes")
115
  with gr.Row():
116
+ refresh_btn = gr.Button("πŸ”„ Refresh")
117
+ inference_btn = gr.Button("πŸ§ͺ Inference Kitchen")
118
+ publish_btn = gr.Button("πŸš€ Publishing Bay")
119
  runs_display = gr.Textbox(label="Your Training Runs", lines=8, interactive=False)
120
  with gr.Accordion("View Raw Logs", open=False):
121
+ run_id_input = gr.Textbox(label="Enter a Run ID")
122
  view_logs_btn = gr.Button("View Logs")
123
  logs_display = gr.Textbox(label="Training Logs", lines=10, interactive=False)
124
  new_run_btn = gr.Button("βž• Start New Process", variant="primary")
125
 
 
126
  with gr.Group(visible=False) as page_inference_ui:
127
  gr.Markdown("### πŸ§ͺ Inference Kitchen")
128
+ inf_run_id_dropdown = gr.Dropdown(label="Select a Completed Model")
129
+ prompt_input = gr.Textbox(label="Your Prompt", lines=3)
130
  infer_btn = gr.Button("Generate Answer")
131
  output_text = gr.Textbox(label="Model's Answer", lines=5, interactive=False)
132
  back_from_inf = gr.Button("⬅️ Back to Processes")
133
 
 
134
  with gr.Group(visible=False) as page_publish_ui:
135
  gr.Markdown("### πŸš€ Publishing Bay")
136
  pub_run_id_dropdown = gr.Dropdown(label="Select a Completed Model to Publish")
137
+ pub_hf_token_input = gr.Textbox(label="Your Hugging Face Token (with write permissions)", type="password")
138
+ pub_description_input = gr.Textbox(label="Model Card Description", lines=4)
 
139
  publish_now_btn = gr.Button("Publish to Hugging Face Hub", variant="primary")
140
  publish_status = gr.Markdown()
141
  back_from_pub = gr.Button("⬅️ Back to Processes")
142
 
 
143
  with gr.Group(visible=False) as page_arch_ui:
144
  gr.Markdown("### πŸ—οΈ Step 2: Choose Your Architecture")
145
  arch_dropdown = gr.Dropdown(["cnn", "rnn", "transformer"], label="Architecture Type")
 
147
  arch_next_btn = gr.Button("Next β†’ Hyperparameters")
148
  arch_analogy = gr.Markdown()
149
  auto_suggestion = gr.Markdown()
150
+
151
  with gr.Group(visible=False) as page_hyper_ui:
152
+ gr.Markdown("### πŸ§‚ Step 3: Season Your Model")
 
153
  lr_input = gr.Number(label="Learning Rate")
154
  epochs_input = gr.Number(label="Epochs", precision=0)
155
  batch_input = gr.Number(label="Batch Size", precision=0)
156
  hyper_next_btn = gr.Button("Start Cooking! 🍲")
157
 
158
+ # ------------------------------ EVENTS ------------------------------
 
 
159
  go_to_signup_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[page_login_ui, page_signup_ui])
160
  go_to_login_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[page_signup_ui, page_login_ui])
161
  login_btn.click(login_action, inputs=[login_user_input, login_pass_input], outputs=[page_login_ui, page_processes_ui, login_msg, runs_display])
162
  signup_btn.click(signup_action, inputs=[signup_user_input, signup_pass_input], outputs=[page_signup_ui, page_login_ui, signup_msg])
163
+
 
164
  refresh_btn.click(page_processes, outputs=runs_display)
165
  view_logs_btn.click(load_run_logs, inputs=run_id_input, outputs=logs_display)
166
+ new_run_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[page_processes_ui, page_arch_ui])
167
  arch_next_btn.click(page_architecture_next, inputs=[arch_dropdown, layers_slider], outputs=[page_arch_ui, page_hyper_ui, arch_analogy, auto_suggestion, lr_input, epochs_input, batch_input])
168
  hyper_next_btn.click(page_hyperparams_next, inputs=[lr_input, epochs_input, batch_input], outputs=[page_hyper_ui, page_processes_ui, runs_display])
169
+
170
+ inference_btn.click(lambda: go_to_page_with_run_list(gr.update(visible=True)), outputs=[page_processes_ui, page_inference_ui, inf_run_id_dropdown])
171
  infer_btn.click(inference_action, inputs=[inf_run_id_dropdown, prompt_input], outputs=output_text)
172
  back_from_inf.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[page_inference_ui, page_processes_ui])
173
 
174
+ publish_btn.click(lambda: go_to_page_with_run_list(gr.update(visible=True)), outputs=[page_processes_ui, page_publish_ui, pub_run_id_dropdown])
 
175
  publish_now_btn.click(publish_action, inputs=[pub_run_id_dropdown, pub_hf_token_input, pub_description_input], outputs=publish_status)
176
  back_from_pub.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[page_publish_ui, page_processes_ui])
177