Update Email Read Allowed.ipynb

This commit is contained in:
Masih Moafi 2025-01-26 15:45:47 +03:30 committed by GitHub
parent e1fff1a36d
commit 5bba80a6dc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,230 +1,110 @@
'use client'; ],
"source": [
import { useState, useEffect, useRef } from 'react'; "from transformers import AutoModelForCausalLM, AutoTokenizer\n",
"from gtts import gTTS\n",
type Message = { "from playsound import playsound\n",
text: string; "import os\n",
sender: 'user' | 'bot'; "\n",
}; "# Load the tokenizer and model for GPT-J\n",
"tokenizer = AutoTokenizer.from_pretrained(\"EleutherAI/gpt-j-6B\")\n",
export default function Chatbot() { "model = AutoModelForCausalLM.from_pretrained(\"EleutherAI/gpt-j-6B\")\n",
const [isOpen, setIsOpen] = useState(false); "\n",
const [messages, setMessages] = useState<Message[]>([]); "# Set the padding token to the EOS token\n",
const [inputText, setInputText] = useState(''); "tokenizer.pad_token = tokenizer.eos_token\n",
const [isLoading, setIsLoading] = useState(false); "\n",
const chatContainerRef = useRef<HTMLDivElement>(null); "def generate_email(professor_name, research_topic, user_name):\n",
" # Email template\n",
const handleSendMessage = async () => { " prompt = f\"\"\"\n",
if (!inputText.trim() || isLoading) return; " Dear Professor {professor_name},\n",
"\n",
try { " I am writing to express my interest in pursuing research under your guidance. My research topic revolves around {research_topic}.\n",
setIsLoading(true); "\n",
const userMessage = inputText.trim(); " I believe that your work in this area is groundbreaking, and I am eager to contribute to your ongoing projects.\n",
setMessages(prev => [...prev, { text: userMessage, sender: 'user' }]); "\n",
setInputText(''); " Best regards,\n",
" {user_name}\n",
// Directly call Ollama API via local tunnel " \"\"\"\n",
const response = await fetch('https://joe-ollama.loca.lt/api/generate', { " # Tokenize input\n",
method: 'POST', " inputs = tokenizer(prompt, return_tensors=\"pt\", truncation=True, padding=True)\n",
headers: { " # Generate email with controlled randomness\n",
'Content-Type': 'application/json', " output = model.generate(\n",
'Authorization': 'Basic ' + btoa('username:password') // Add your auth " inputs[\"input_ids\"],\n",
}, " attention_mask=inputs[\"attention_mask\"],\n",
body: JSON.stringify({ " max_length=len(inputs[\"input_ids\"][0]) + 100,\n",
model: 'llama3', " do_sample=True, # Set to True to use temperature and top_p\n",
prompt: userMessage, " temperature=0.7,\n",
stream: false, " top_p=0.9,\n",
options: { " pad_token_id=tokenizer.eos_token_id\n",
temperature: 0.7, " )\n",
max_tokens: 500 " # Decode and return the text\n",
} " generated_email = tokenizer.decode(output[0], skip_special_tokens=True)\n",
}), " return generated_email.strip()\n",
}); "\n",
"def text_to_speech(text, output_file=\"email.mp3\", lang='en'):\n",
if (!response.ok) throw new Error('Failed to get response'); " try:\n",
" if os.path.exists(output_file):\n",
const data = await response.json(); " os.remove(output_file)\n",
setMessages(prev => [...prev, { text: data.response, sender: 'bot' }]); " tts = gTTS(text, lang=lang)\n",
} catch (error) { " tts.save(output_file)\n",
console.error('Chat error:', error); " print(f\"Speech saved to {output_file}\")\n",
setMessages(prev => [...prev, { " except Exception as e:\n",
text: "Sorry, I'm having trouble connecting. Please try again later.", " print(f\"Error generating speech: {e}\")\n",
sender: 'bot' "\n",
}]); "def play_sound(file_path):\n",
} finally { " if not os.path.exists(file_path):\n",
setIsLoading(false); " print(\"File not found.\")\n",
} " return\n",
}; " try:\n",
" # Using playsound\n",
useEffect(() => { " playsound(file_path)\n",
if (chatContainerRef.current) { " print(\"\\nEmail is being read aloud.\")\n",
chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight; " except Exception as e:\n",
} " print(f\"Error playing sound with playsound: {e}\")\n",
}, [messages]); "\n",
"# Input data\n",
return ( "professor_name = input(\"Enter the professor's name: \")\n",
<div style={{ position: 'fixed', bottom: '20px', right: '29.6px', zIndex: 1000 }}> "research_topic = input(\"Enter your research topic: \")\n",
{isOpen && ( "user_name = input(\"Enter your name: \")\n",
<div style={chatWindowStyle}> "\n",
<div style={headerStyle}> "# Generate and print the email\n",
<div style={titleStyle}>Chat with Joe's AI</div> "email = generate_email(professor_name, research_topic, user_name)\n",
<button onClick={() => setIsOpen(false)} style={closeButtonStyle}> "print(\"\\nGenerated Email:\\n\")\n",
× "print(email)\n",
</button> "\n",
</div> "# Convert the email to speech\n",
"text_to_speech(email)\n",
<div ref={chatContainerRef} style={messageContainerStyle}> "\n",
{messages.map((msg, index) => ( "# Play the generated speech\n",
<div key={index} style={messageBubbleStyle(msg.sender)}> "play_sound(\"email.mp3\")"
<span style={textStyle(msg.sender)}> ]
{msg.text} },
</span> {
</div> "cell_type": "code",
))} "execution_count": null,
{isLoading && ( "id": "89bc527f-4f37-44d3-8454-52a980cf6038",
<div style={loadingStyle}> "metadata": {},
<div className="dot-flashing" /> "outputs": [],
</div> "source": []
)} }
</div> ],
"metadata": {
<div style={inputContainerStyle}> "kernelspec": {
<input "display_name": "Python 3 (ipykernel)",
type="text" "language": "python",
value={inputText} "name": "python3"
onChange={(e) => setInputText(e.target.value)} },
onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()} "language_info": {
style={inputStyle} "codemirror_mode": {
placeholder="Ask me anything..." "name": "ipython",
disabled={isLoading} "version": 3
/> },
<button "file_extension": ".py",
onClick={handleSendMessage} "mimetype": "text/x-python",
style={sendButtonStyle} "name": "python",
disabled={isLoading} "nbconvert_exporter": "python",
> "pygments_lexer": "ipython3",
{isLoading ? '...' : 'Send'} "version": "3.8.19"
</button> }
</div> },
</div> "nbformat": 4,
)} "nbformat_minor": 5
{!isOpen && (
<button
onClick={() => setIsOpen(true)}
style={toggleButtonStyle}
>
💬
</button>
)}
</div>
);
}
// Style constants
const chatWindowStyle = {
width: '350px',
border: '1px solid #e5e7eb',
borderRadius: '12px',
padding: '16px',
backgroundColor: '#ffffff',
boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
};
const headerStyle = {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '16px',
};
const titleStyle = {
fontSize: '18px',
fontWeight: '600',
color: '#1f2937',
};
const closeButtonStyle = {
padding: '8px',
borderRadius: '50%',
border: 'none',
backgroundColor: '#31616c',
color: '#fff',
cursor: 'pointer',
fontWeight: '600',
width: '32px',
height: '32px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
};
const messageContainerStyle = {
height: '330px',
overflowY: 'auto',
marginBottom: '16px',
padding: '8px',
backgroundColor: '#f3f4f6',
borderRadius: '8px',
};
const messageBubbleStyle = (sender: 'user' | 'bot') => ({
textAlign: sender === 'user' ? 'right' : 'left',
margin: '8px 0',
});
const textStyle = (sender: 'user' | 'bot') => ({
display: 'inline-block',
padding: '8px 12px',
borderRadius: '12px',
backgroundColor: sender === 'user' ? '#31616c' : '#e5e7eb',
color: sender === 'user' ? '#fff' : '#1f2937',
maxWidth: '80%',
wordWrap: 'break-word' as const,
});
const inputContainerStyle = {
display: 'flex',
gap: '8px',
};
const inputStyle = {
flex: 1,
padding: '8px',
borderRadius: '8px',
border: '1px solid #e5e7eb',
backgroundColor: '#ffffff',
color: '#1f2937',
outline: 'none',
};
const sendButtonStyle = {
padding: '8px 16px',
borderRadius: '8px',
border: 'none',
backgroundColor: '#31616c',
color: '#fff',
cursor: 'pointer',
fontWeight: '600',
};
const toggleButtonStyle = {
padding: '12px',
borderRadius: '50%',
border: 'none',
backgroundColor: '#31616c',
color: '#fff',
cursor: 'pointer',
boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '48px',
height: '48px',
};
const loadingStyle = {
display: 'flex',
justifyContent: 'center',
padding: '8px',
};