stanley-00 commited on
Commit
cc8c521
·
verified ·
1 Parent(s): 5a9487b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -0
app.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ import gc
4
+ import os
5
+ import shutil
6
+ import torch
7
+ import psutil
8
+
9
+ # Define path for HF cache to clean
10
+ HF_CACHE_DIR = os.path.expanduser("~/.cache/huggingface/hub")
11
+
12
+ def get_system_stats():
13
+ """Returns a dictionary of current system metrics with formatted strings."""
14
+ mem = psutil.virtual_memory()
15
+ disk = psutil.disk_usage('/')
16
+ return {
17
+ "CPU": f"{psutil.cpu_percent(interval=1)}%",
18
+ "Memory": f"{round(mem.used / (1024**3), 2)} / {round(mem.total / (1024**3), 2)} GB",
19
+ "Disk": f"{round(disk.used / (1024**3), 2)} / {round(disk.total / (1024**3), 2)} GB"
20
+ }
21
+
22
+ def load_new_model(model_id):
23
+ # Clear old model from memory
24
+ gc.collect()
25
+ if torch.cuda.is_available():
26
+ torch.cuda.empty_cache()
27
+
28
+ try:
29
+ # Load a text-generation pipeline
30
+ pipe = pipeline("text-generation", model=model_id)
31
+ return pipe, f"Successfully loaded {model_id}"
32
+ except Exception as e:
33
+ return None, f"Error loading model: {str(e)}"
34
+
35
+ def run_inference(model, system_prompt, user_prompt):
36
+ if not model:
37
+ return "Please load a model first."
38
+
39
+ # Combine prompts
40
+ full_prompt = f"System: {system_prompt}\nUser: {user_prompt}"
41
+
42
+ # Run inference
43
+ result = model(full_prompt, max_new_tokens=50)
44
+ return result[0]['generated_text']
45
+
46
+ def clean_cache():
47
+ if os.path.exists(HF_CACHE_DIR):
48
+ shutil.rmtree(HF_CACHE_DIR)
49
+ os.makedirs(HF_CACHE_DIR)
50
+ return "Cache cleaned successfully!"
51
+ return "Cache directory not found."
52
+
53
+ # Gradio Interface
54
+ with gr.Blocks(title="Small Model Tester") as app:
55
+ gr.Markdown("# Advanced HF Model Tester (Free Tier)")
56
+
57
+ # Stats Section
58
+ with gr.Accordion("System Monitoring", open=True):
59
+ stats_output = gr.JSON(label="Live System Stats")
60
+ # Gradio timer to update stats every 5 seconds
61
+ gr.Timer(5).tick(get_system_stats, None, stats_output)
62
+
63
+ current_model = gr.State(None)
64
+
65
+ with gr.Row():
66
+ model_id_input = gr.Textbox(label="Model ID", value="distilgpt2", placeholder="e.g., distilgpt2, tiny-llama/tiny-llama-1.1b")
67
+ load_btn = gr.Button("Load Model")
68
+
69
+ status_output = gr.Markdown("Status: Waiting to load model...")
70
+
71
+ with gr.Row():
72
+ system_prompt = gr.Textbox(label="System Prompt", placeholder="You are a helpful assistant.")
73
+ user_prompt = gr.Textbox(label="User Prompt", placeholder="Hello!")
74
+
75
+ run_btn = gr.Button("Run Inference", variant="primary")
76
+ output_text = gr.Textbox(label="Result")
77
+
78
+ clean_btn = gr.Button("Clean Cache")
79
+
80
+ # Events
81
+ load_btn.click(
82
+ fn=load_new_model,
83
+ inputs=[model_id_input],
84
+ outputs=[current_model, status_output]
85
+ )
86
+
87
+ run_btn.click(
88
+ fn=run_inference,
89
+ inputs=[current_model, system_prompt, user_prompt],
90
+ outputs=[output_text]
91
+ )
92
+
93
+ clean_btn.click(fn=clean_cache, outputs=[status_output])
94
+
95
+ if __name__ == "__main__":
96
+ app.launch()