Hercule66 commited on
Commit
69aef1c
·
verified ·
1 Parent(s): 8e93cad

Update app.py

Browse files

Modification du fichier de base pour l'adapter à mon modèle fine-tunner

Files changed (1) hide show
  1. app.py +198 -38
app.py CHANGED
@@ -1,6 +1,99 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  def respond(
6
  message,
@@ -9,62 +102,129 @@ def respond(
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
  import gradio as gr
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+ from peft import PeftModel
5
+ from huggingface_hub import login
6
+ import os
7
 
8
+ # Configuration du modèle
9
+ MODEL_NAME = "Hercule66/qwen3-freelance-chatbot-tpu"
10
+ BASE_MODEL_NAME = "Qwen/Qwen3-0.6B"
11
+
12
+ # Variables globales pour le modèle et tokenizer
13
+ model = None
14
+ tokenizer = None
15
+
16
+ def load_model():
17
+ """Charge le modèle et le tokenizer une seule fois"""
18
+ global model, tokenizer
19
+
20
+ if model is None or tokenizer is None:
21
+ try:
22
+ # Authentification avec le token HF
23
+ hf_token = os.getenv("HF_TOKEN")
24
+ if hf_token:
25
+ login(token=hf_token)
26
+
27
+ # Chargement du tokenizer
28
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
29
+
30
+ # Chargement du modèle de base
31
+ base_model = AutoModelForCausalLM.from_pretrained(
32
+ BASE_MODEL_NAME,
33
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
34
+ device_map="auto" if torch.cuda.is_available() else None
35
+ )
36
+
37
+ # Chargement du modèle fine-tuné avec PEFT
38
+ model = PeftModel.from_pretrained(base_model, MODEL_NAME)
39
+
40
+ print("Modèle chargé avec succès!")
41
+
42
+ except Exception as e:
43
+ print(f"Erreur lors du chargement du modèle: {e}")
44
+ raise e
45
+
46
+ def generate_proposal(job_posting, max_tokens=500, temperature=0.7, top_p=0.9):
47
+ """Génère une proposition basée sur le job posting"""
48
+ try:
49
+ # Format du prompt comme dans votre code original
50
+ messages = [{
51
+ "role": "user",
52
+ "content": ("1. Check if the job is urgent."
53
+ "2. Review the provided details to understand the scope and requirements."
54
+ "3. Identify potential challenges and risks associated with the job."
55
+ "4. Determine the ideal candidate's profile and experience."
56
+ "5. Create a detailed job description highlighting the key tasks and responsibilities."
57
+ "6. Suggest a starting budget based on the complexity and time required."
58
+ "7. Finalize the job posting with all necessary information.\n"
59
+ f"{job_posting}")
60
+ }]
61
+
62
+ # Préparation des inputs
63
+ inputs = tokenizer.apply_chat_template(
64
+ messages,
65
+ add_generation_prompt=True,
66
+ tokenize=True,
67
+ return_dict=True,
68
+ return_tensors="pt"
69
+ )
70
+
71
+ # Déplacement vers le device du modèle si nécessaire
72
+ if hasattr(model, 'device'):
73
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
74
+
75
+ # Génération
76
+ with torch.no_grad():
77
+ outputs = model.generate(
78
+ **inputs,
79
+ max_new_tokens=max_tokens,
80
+ temperature=temperature,
81
+ top_p=top_p,
82
+ repetition_penalty=1.1,
83
+ do_sample=True,
84
+ pad_token_id=tokenizer.eos_token_id
85
+ )
86
+
87
+ # Décodage de la réponse
88
+ response = tokenizer.decode(
89
+ outputs[0][inputs["input_ids"].shape[-1]:],
90
+ skip_special_tokens=True
91
+ )
92
+
93
+ return response.strip()
94
+
95
+ except Exception as e:
96
+ return f"Erreur lors de la génération: {str(e)}"
97
 
98
  def respond(
99
  message,
 
102
  max_tokens,
103
  temperature,
104
  top_p,
 
105
  ):
106
  """
107
+ Fonction de réponse adaptée pour votre modèle de freelance chatbot
108
  """
109
+ global model, tokenizer
110
+
111
+ # Chargement du modèle si nécessaire
112
+ if model is None or tokenizer is None:
113
+ load_model()
114
+
115
+ try:
116
+ # Si le message ressemble à un job posting, utiliser la fonction spécialisée
117
+ if any(keyword in message.lower() for keyword in ['job', 'project', 'freelance', 'budget', 'requirements']):
118
+ response = generate_proposal(message, max_tokens, temperature, top_p)
119
+ else:
120
+ # Pour les autres messages, utiliser une approche plus générale
121
+ full_conversation = system_message + "\n"
122
+
123
+ # Ajouter l'historique
124
+ for msg in history:
125
+ if msg["role"] == "user":
126
+ full_conversation += f"User: {msg['content']}\n"
127
+ else:
128
+ full_conversation += f"Assistant: {msg['content']}\n"
129
+
130
+ full_conversation += f"User: {message}\nAssistant:"
131
+
132
+ # Tokenisation
133
+ inputs = tokenizer(
134
+ full_conversation,
135
+ return_tensors="pt",
136
+ truncate=True,
137
+ max_length=2048
138
+ )
139
+
140
+ if hasattr(model, 'device'):
141
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
142
 
143
+ # Génération
144
+ with torch.no_grad():
145
+ outputs = model.generate(
146
+ **inputs,
147
+ max_new_tokens=max_tokens,
148
+ temperature=temperature,
149
+ top_p=top_p,
150
+ repetition_penalty=1.1,
151
+ do_sample=True,
152
+ pad_token_id=tokenizer.eos_token_id
153
+ )
154
 
155
+ response = tokenizer.decode(
156
+ outputs[0][inputs["input_ids"].shape[-1]:],
157
+ skip_special_tokens=True
158
+ )
159
+
160
+ # Retourner la réponse de manière progressive (streaming)
161
+ current_response = ""
162
+ for char in response.strip():
163
+ current_response += char
164
+ yield current_response
165
+
166
+ except Exception as e:
167
+ yield f"Erreur: {str(e)}"
168
 
169
+ # Interface Gradio
 
 
 
 
 
 
170
  chatbot = gr.ChatInterface(
171
  respond,
172
  type="messages",
173
+ title="🚀 Freelance Proposal Generator",
174
+ description="Chatbot spécialisé dans la génération de propositions freelance. Collez votre job posting pour obtenir une analyse détaillée!",
175
  additional_inputs=[
176
+ gr.Textbox(
177
+ value="You are a professional freelance consultant specialized in analyzing job postings and creating winning proposals. You help freelancers understand project requirements, identify risks, and suggest appropriate budgets.",
178
+ label="System message",
179
+ lines=3
180
+ ),
181
+ gr.Slider(
182
+ minimum=50,
183
+ maximum=1000,
184
+ value=500,
185
+ step=50,
186
+ label="Max new tokens"
187
+ ),
188
+ gr.Slider(
189
+ minimum=0.1,
190
+ maximum=1.0,
191
+ value=0.7,
192
+ step=0.1,
193
+ label="Temperature"
194
+ ),
195
  gr.Slider(
196
  minimum=0.1,
197
  maximum=1.0,
198
+ value=0.9,
199
  step=0.05,
200
  label="Top-p (nucleus sampling)",
201
  ),
202
  ],
203
+ examples=[
204
+ ["Analyze this web development project for me: 'Need a responsive e-commerce website with payment integration. Budget: $500-1000'"],
205
+ ["What should I consider for this data analysis project: 'Looking for someone to analyze sales data and create visualizations. Urgent deadline: 3 days'"],
206
+ ["Help me understand this mobile app development job posting..."]
207
+ ]
208
  )
209
 
210
+ # Interface principale
211
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
212
+ gr.Markdown("# 🎯 Freelance Proposal Assistant")
213
+ gr.Markdown("*Powered by Qwen3 fine-tuned model*")
214
+
215
  chatbot.render()
216
+
217
+ gr.Markdown("""
218
+ ### 💡 Comment utiliser:
219
+ 1. **Collez un job posting** dans le chat
220
+ 2. Le modèle analysera automatiquement les exigences
221
+ 3. Vous recevrez une analyse détaillée avec suggestions de budget
222
+ 4. Ajustez les paramètres si nécessaire
223
+ """)
224
 
225
  if __name__ == "__main__":
226
+ # Chargement initial du modèle
227
+ print("Chargement du modèle...")
228
+ load_model()
229
+ print("Démarrage de l'interface...")
230
+ demo.launch()