mubashirhussaindev commited on
Commit
8b5128e
Β·
verified Β·
1 Parent(s): 6db8a9e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -30
app.py CHANGED
@@ -9,7 +9,7 @@ import re
9
  from datetime import datetime
10
  import os
11
 
12
- # Load SMTP credentials from Hugging Face Secrets
13
  SMTP_SERVER = "mail.mubashirdev.com"
14
  SMTP_PORT = 465
15
  SMTP_USERNAME = os.getenv("SMTP_USERNAME")
@@ -17,7 +17,7 @@ SMTP_PASSWORD = os.getenv("SMTP_PASSWORD")
17
  FROM_EMAIL = SMTP_USERNAME
18
  FROM_NAME = "Mubashir Hussain"
19
 
20
- # Send email
21
  def send_email(to_email, subject, body):
22
  try:
23
  msg = MIMEMultipart()
@@ -32,54 +32,86 @@ def send_email(to_email, subject, body):
32
  server.send_message(msg)
33
  return True
34
  except Exception as e:
35
- print(f"Email error: {e}")
36
  return False
37
 
38
  # Load model
39
- tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-large")
40
- model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-large")
41
 
42
- # Chat context
43
  context = """
44
  I am Mubashir Hussain, a Full Stack Developer from Lahore, Pakistan. I specialize in Laravel, Livewire, MERN Stack, Vue, and Angular. I help startups build secure and scalable web apps.
45
- You can ask me about:
46
  - My services
47
  - My portfolio (CodeConnect, Mobile Repair App)
48
  - My blog posts
49
  - Or book an appointment!
50
  """
51
 
52
- chat_history = []
53
- appointment_pattern = r"appointment.*?on\s*(\d{4}-\d{2}-\d{2})\s*at\s*(\d{2}:\d{2}).*?email\s*is\s*([\w\.-]+@[\w\.-]+)"
 
54
 
55
- # Chat function
56
- def chat(message):
57
- global chat_history
58
- full_input = f"{context}\nUser: {message}\nBot:"
59
- new_input = tokenizer.encode(full_input + tokenizer.eos_token, return_tensors="pt")
60
- bot_input = new_input if not chat_history else torch.cat([torch.LongTensor(chat_history), new_input], dim=-1)
61
- output = model.generate(bot_input, max_length=500, pad_token_id=tokenizer.eos_token_id)
62
- reply = tokenizer.decode(output[0], skip_special_tokens=True).split("Bot:")[-1].strip()
63
- chat_history.append(new_input[0].tolist())
64
 
65
- # Handle appointments
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  match = re.search(appointment_pattern, message.lower())
67
  if match:
68
  date_str, time_str, email = match.groups()
69
  try:
70
- appointment_time = datetime.strptime(f"{date_str} {time_str}", "%Y-%m-%d %H:%M")
71
- admin_msg = f"New Appointment:\nDate: {date_str}\nTime: {time_str}\nEmail: {email}"
 
 
72
  user_msg = f"Hi,\n\nYour appointment with Mubashir is confirmed for {date_str} at {time_str}.\n\nRegards,\nMubashir Hussain\nhttps://mubashirdev.com"
 
73
  send_email("admin@mubashirdev.com", "πŸ“… New Appointment", admin_msg)
74
  send_email(email, "βœ… Appointment Confirmed", user_msg)
75
- reply += f"\n\nβœ… Your appointment on {date_str} at {time_str} is confirmed. A confirmation email has been sent to {email}."
76
- except:
77
- reply += "\n❌ Error parsing date/time. Use format: 'I want an appointment on YYYY-MM-DD at HH:MM. My email is you@example.com'."
78
- return reply
 
 
 
 
 
 
 
 
79
 
80
  # Gradio UI
81
- gr.ChatInterface(
82
- fn=chat,
83
- title="Mubashir Dev Chatbot",
84
- description="Ask about my services or book an appointment.\nTry: I want an appointment on 2025-06-01 at 14:00. My email is you@example.com"
85
- ).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  from datetime import datetime
10
  import os
11
 
12
+ # Load SMTP credentials securely
13
  SMTP_SERVER = "mail.mubashirdev.com"
14
  SMTP_PORT = 465
15
  SMTP_USERNAME = os.getenv("SMTP_USERNAME")
 
17
  FROM_EMAIL = SMTP_USERNAME
18
  FROM_NAME = "Mubashir Hussain"
19
 
20
+ # Email sender
21
  def send_email(to_email, subject, body):
22
  try:
23
  msg = MIMEMultipart()
 
32
  server.send_message(msg)
33
  return True
34
  except Exception as e:
35
+ print(f"[Email Error]: {e}")
36
  return False
37
 
38
  # Load model
39
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
40
+ model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
41
 
42
+ # Chatbot persona
43
  context = """
44
  I am Mubashir Hussain, a Full Stack Developer from Lahore, Pakistan. I specialize in Laravel, Livewire, MERN Stack, Vue, and Angular. I help startups build secure and scalable web apps.
45
+ Ask me about:
46
  - My services
47
  - My portfolio (CodeConnect, Mobile Repair App)
48
  - My blog posts
49
  - Or book an appointment!
50
  """
51
 
52
+ # Chat session history (Gradio state-compatible)
53
+ def respond(message, chat_history=[]):
54
+ appointment_pattern = r"appointment.*on\s*(\d{4}-\d{2}-\d{2})\s*at\s*(\d{2}:\d{2}).*?email\s*is\s*([\w\.-]+@[\w\.-]+)"
55
 
56
+ # Construct full prompt
57
+ full_input = f"{context}\n" + "\n".join(
58
+ [f"User: {u}\nBot: {b}" for u, b in chat_history]
59
+ ) + f"\nUser: {message}\nBot:"
 
 
 
 
 
60
 
61
+ input_ids = tokenizer.encode(full_input + tokenizer.eos_token, return_tensors="pt")
62
+ output_ids = model.generate(
63
+ input_ids,
64
+ max_length=1000,
65
+ pad_token_id=tokenizer.eos_token_id,
66
+ temperature=0.7,
67
+ top_p=0.95,
68
+ top_k=50
69
+ )
70
+
71
+ output_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
72
+ reply = output_text.split("Bot:")[-1].strip()
73
+
74
+ # Handle appointment
75
  match = re.search(appointment_pattern, message.lower())
76
  if match:
77
  date_str, time_str, email = match.groups()
78
  try:
79
+ datetime.strptime(f"{date_str} {time_str}", "%Y-%m-%d %H:%M")
80
+
81
+ # Send emails
82
+ admin_msg = f"πŸ“… New Appointment Request:\nDate: {date_str}\nTime: {time_str}\nEmail: {email}"
83
  user_msg = f"Hi,\n\nYour appointment with Mubashir is confirmed for {date_str} at {time_str}.\n\nRegards,\nMubashir Hussain\nhttps://mubashirdev.com"
84
+
85
  send_email("admin@mubashirdev.com", "πŸ“… New Appointment", admin_msg)
86
  send_email(email, "βœ… Appointment Confirmed", user_msg)
87
+
88
+ reply += f"\n\nβœ… Appointment on {date_str} at {time_str} is confirmed. A confirmation email was sent to {email}."
89
+ except Exception as e:
90
+ print(f"[Parse Error]: {e}")
91
+ reply += "\n❌ Please use the format: 'I want an appointment on YYYY-MM-DD at HH:MM. My email is you@example.com'."
92
+
93
+ chat_history.append((message, reply))
94
+ return chat_history, chat_history
95
+
96
+ # Reset function
97
+ def reset():
98
+ return [], []
99
 
100
  # Gradio UI
101
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
102
+ gr.Markdown("## πŸ‘‹ Mubashir Dev Chatbot")
103
+ gr.Markdown("Ask me anything about my work, or book an appointment.\nExample: `I want an appointment on 2025-06-01 at 14:00. My email is you@example.com`")
104
+
105
+ chatbot = gr.Chatbot()
106
+ msg = gr.Textbox(label="Your message")
107
+ state = gr.State([])
108
+
109
+ with gr.Row():
110
+ send_btn = gr.Button("Send")
111
+ clear_btn = gr.Button("Reset Chat")
112
+
113
+ send_btn.click(respond, inputs=[msg, state], outputs=[chatbot, state])
114
+ clear_btn.click(reset, inputs=[], outputs=[chatbot, state])
115
+
116
+ # Run it
117
+ demo.launch()