sepo25 commited on
Commit
371d180
·
verified ·
1 Parent(s): bfeaaec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -59
app.py CHANGED
@@ -1,70 +1,163 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
 
21
- messages.extend(history)
 
 
 
22
 
23
- messages.append({"role": "user", "content": message})
 
 
24
 
25
- response = ""
 
 
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  minimum=0.1,
55
  maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
-
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
67
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
 
69
  if __name__ == "__main__":
70
- demo.launch()
 
1
+ # app.py - Hugging Face Space Application
2
+ # This creates a chat interface for your fine-tuned model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
+ import gradio as gr
5
+ import torch
6
+ from transformers import AutoTokenizer, AutoModelForCausalLM
7
+ from peft import PeftModel
8
 
9
+ # Configuration
10
+ BASE_MODEL = "microsoft/phi-2"
11
+ ADAPTER_MODEL = "sepo25/my-finetuned-model"
12
 
13
+ # Global variables to store loaded model
14
+ model = None
15
+ tokenizer = None
16
 
17
+ def load_model():
18
+ """Load the base model and fine-tuned adapter"""
19
+ global model, tokenizer
20
+
21
+ print("Loading model... This may take a minute.")
22
+
23
+ # Load tokenizer
24
+ tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
25
+ tokenizer.pad_token = tokenizer.eos_token
26
+
27
+ # Load base model
28
+ base_model = AutoModelForCausalLM.from_pretrained(
29
+ BASE_MODEL,
30
+ torch_dtype=torch.float16,
31
+ device_map="auto",
32
+ trust_remote_code=True
33
+ )
34
+
35
+ # Load fine-tuned adapter
36
+ model = PeftModel.from_pretrained(base_model, ADAPTER_MODEL)
37
+
38
+ print("Model loaded successfully!")
39
+ return model, tokenizer
40
 
41
+ def generate_response(message, chat_history, temperature=0.7, max_tokens=200):
42
+ """Generate a response from the model"""
43
+ global model, tokenizer
44
+
45
+ # Load model if not already loaded
46
+ if model is None or tokenizer is None:
47
+ load_model()
48
+
49
+ # Format the prompt
50
+ prompt = f"### Instruction:\n{message}\n\n### Response:\n"
51
+
52
+ # Tokenize
53
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
54
+
55
+ # Generate response
56
+ with torch.no_grad():
57
+ outputs = model.generate(
58
+ **inputs,
59
+ max_new_tokens=max_tokens,
60
+ temperature=temperature,
61
+ do_sample=True,
62
+ top_p=0.9,
63
+ pad_token_id=tokenizer.eos_token_id
64
+ )
65
+
66
+ # Decode response
67
+ full_response = tokenizer.decode(outputs[0], skip_special_tokens=True)
68
+
69
+ # Extract only the response part (after "### Response:")
70
+ if "### Response:" in full_response:
71
+ response = full_response.split("### Response:")[-1].strip()
72
+ else:
73
+ response = full_response
74
+
75
+ # Update chat history
76
+ chat_history.append((message, response))
77
+
78
+ return "", chat_history
79
 
80
+ def clear_chat():
81
+ """Clear the chat history"""
82
+ return [], []
83
 
84
+ # Create Gradio interface
85
+ with gr.Blocks(title="My Fine-tuned Model Chat", theme=gr.themes.Soft()) as demo:
86
+
87
+ gr.Markdown(
88
+ """
89
+ # 🤖 Chat with My Fine-tuned Model
90
+
91
+ This model has been fine-tuned on custom text data and can answer questions and provide summaries.
92
+
93
+ **Tips:**
94
+ - Ask questions about the content it was trained on
95
+ - Request summaries of information
96
+ - Be specific in your questions for best results
97
+ """
98
+ )
99
+
100
+ chatbot = gr.Chatbot(
101
+ label="Conversation",
102
+ height=400,
103
+ show_label=True
104
+ )
105
+
106
+ with gr.Row():
107
+ msg = gr.Textbox(
108
+ label="Your message",
109
+ placeholder="Type your question here...",
110
+ scale=4
111
+ )
112
+ submit_btn = gr.Button("Send", variant="primary", scale=1)
113
+
114
+ with gr.Accordion("⚙️ Advanced Settings", open=False):
115
+ temperature = gr.Slider(
116
  minimum=0.1,
117
  maximum=1.0,
118
+ value=0.7,
119
+ step=0.1,
120
+ label="Temperature (higher = more creative)",
121
+ )
122
+ max_tokens = gr.Slider(
123
+ minimum=50,
124
+ maximum=500,
125
+ value=200,
126
+ step=50,
127
+ label="Max tokens (response length)",
128
+ )
129
+
130
+ with gr.Row():
131
+ clear_btn = gr.Button("🗑️ Clear Chat")
132
+
133
+ gr.Markdown(
134
+ """
135
+ ---
136
+ ### Example Questions:
137
+ - "What is this text about?"
138
+ - "Summarize the main points"
139
+ - "Tell me about [specific topic from your text]"
140
+ """
141
+ )
142
+
143
+ # Event handlers
144
+ submit_btn.click(
145
+ generate_response,
146
+ inputs=[msg, chatbot, temperature, max_tokens],
147
+ outputs=[msg, chatbot]
148
+ )
149
+
150
+ msg.submit(
151
+ generate_response,
152
+ inputs=[msg, chatbot, temperature, max_tokens],
153
+ outputs=[msg, chatbot]
154
+ )
155
+
156
+ clear_btn.click(
157
+ clear_chat,
158
+ outputs=[chatbot, msg]
159
+ )
160
 
161
+ # Launch the app
162
  if __name__ == "__main__":
163
+ demo.launch()