Certainly! Below is the complete code for each file in the ChatGPT-like web application with React for the frontend and Node.js (Express) for the backend, including enhancements for file uploads, error handling, and UI improvements.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
8. chatgpt-react-app/.env
code
REACT_APP_BACKEND_URL=http://localhost:5000
9. chatgpt-react-app/.gitignore
code
node_modules/
.env
build/
Installation and Set-Up Guide
Once you've created the folder structure and added all the above files into their respective folders, follow these steps to set up both the backend and frontend applications:
Prerequisites
Ensure you have the following installed on your system:
Node.js (v18.x or higher)
npm (comes with Node.js)
Git
Backend Setup (Node.js)
Navigate to the chatgpt-backend directory:
bash
cd ~/Documents/Code/chatgpt-backend
Install the required dependencies:
bash
npm install express cors axios dotenv multer pdf-parse uuid
You should see the application open in your default web browser at http://localhost:3000.
Testing File Uploads
Test text messages: Type a simple message and click "Send".
Upload images: Drag and drop an image file and send it.
Upload PDFs: Drag and drop a PDF file and send it.
Check for unsupported file types: Attempt to upload a file type not allowed and see the appropriate error message.
Conclusion
You've created a full-fledged ChatGPT-like application that handles text, images, and PDFs, complete with error handling and UI enhancements. These enhancements improve usability and enrich the user experience while engaging with your application.
If you have further questions or need assistance with specific features, feel free to ask!
make the ui look better and files uploaded are not shown, fix that
Certainly! Let's enhance your ChatGPT-like application by improving the user interface (UI) and ensuring that uploaded files (images and PDFs) are properly displayed within the chat. Below are the steps and updated code snippets to achieve these improvements.
Overview of Enhancements
UI Enhancements:
Modernize the Chat Interface: Improve the aesthetics with better colors, spacing, and chat bubble designs.
Responsive Design: Ensure the application looks good on various screen sizes.
Loading Indicators: Use spinners for better visual feedback during API calls.
Enhanced Error Messages: Display errors in a more user-friendly manner.
Displaying Uploaded Files:
Images: Show images directly in the chat as part of the user messages.
PDFs: Provide thumbnail previews or download links for PDF files.
Let's implement these enhancements step-by-step.
1. Frontend Enhancements (React)
1.1. Updated App.jsx
We'll modify App.jsx to handle the display of uploaded files. Specifically, we'll:
Read Uploaded Files: Convert images to Data URLs for display. For PDFs, provide a download link.
Display Files in Chat: Add the uploaded files as part of the chat messages.
Improve UI Components: Enhance the overall look and feel.
For a more engaging UI, you can add a background image to the chat window. Place an image (e.g., chat-background.png) in the public folder and reference it in App.css. Ensure the image is appropriately sized and optimized for web use.
css
/* chatgpt-react-app/src/App.css */
/* ... existing styles ... */
.chat-window {
/* ... existing styles ... */
background-image: url('/chat-background.png'); /* Ensure this file exists in the public folder */
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
If you choose not to use a background image, you can omit or comment out these lines.
2. Backend Adjustments (Optional)
To facilitate the display of uploaded PDFs, ensure that the backend serves the uploads directory correctly and handles filename uniqueness to prevent conflicts.
Note: The existing backend setup already serves the /uploads folder as static. However, to allow access via filenames, ensure that when saving uploaded files, their original names are preserved or mapped accordingly.
Here's an optional improvement to the ChatController.js to return the filename after processing:
javascript
// chatgpt-backend/controllers/ChatController.js
// ... existing imports and code ...
const chatWithGPT = async (req, res) => {
const { message, model } = req.body;
let imageDataUrls = [];
let pdfTexts = [];
let uploadedFileName = null; // Track uploaded file name
if (!message && !req.file) {
return res.status(400).json({ error: 'No message or file provided.' });
}
const selectedModel = model || 'gpt-3.5-turbo';
if (!SUPPORTED_MODELS.includes(selectedModel)) {
return res.status(400).json({ error: 'Unsupported model selected.' });
}
if (req.file) {
const file = req.file;
uploadedFileName = file.filename; // Store unique filename
const filePath = path.join(__dirname, '..', 'uploads', file.filename);
try {
if (file.mimetype.startsWith('image/')) {
const imageBuffer = fs.readFileSync(filePath);
const base64Image = imageBuffer.toString('base64');
const dataUrl = `data:${file.mimetype};base64,${base64Image}`;
imageDataUrls.push(dataUrl);
} else if (file.mimetype === 'application/pdf') {
const pdfBuffer = fs.readFileSync(filePath);
const pdfData = await pdfParse(pdfBuffer);
const text = pdfData.text.trim();
if (text.length > 0) {
pdfTexts.push(text);
} else {
return res.status(400).json({ error: 'PDF contains no extractable text.' });
}
}
} catch (err) {
console.error('Error processing uploaded file:', err);
return res.status(500).json({ error: 'Failed to process the uploaded file.' });
}
}
const messagesToSend = [];
if (message) {
messagesToSend.push({ role: 'user', content: message });
}
imageDataUrls.forEach((dataUrl) => {
messagesToSend.push({
role: 'user',
content: [
{ type: 'text', text: 'Here is an image for you to analyze.' },
{ type: 'image_url', image_url: { url: dataUrl, detail: 'high' } },
],
});
});
pdfTexts.forEach((text) => {
messagesToSend.push({ role: 'user', content: text });
});
try {
const response = await axios.post(
'https://api.openai.com/v1/chat/completions',
{ model: selectedModel, messages: messagesToSend, temperature: 0.7 },
{ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${OPENAI_API_KEY}` } }
);
const botReply = response.data.choices[0].message.content.trim();
// Include the uploaded file name in the response if exists
res.json({ reply: botReply, uploadedFileName });
} catch (error) {
console.error('Error communicating with OpenAI:', error.response?.data || error.message);
res.status(500).json({ error: 'Failed to fetch response from OpenAI.' });
}
};
module.exports = { chatWithGPT };
With this change, the backend includes the uploadedFileName in the response, which can be leveraged by the frontend if needed. However, our frontend modification already assumes that the file is accessible via its name in the /uploads directory.
3. Installation and Deployment
After updating the code, ensure both the backend and frontend are reinstalled and restarted to apply the changes.
3.1. Backend Setup
Navigate to the Backend Directory:
bash
cd ~/Documents/Code/chatgpt-backend
Install Dependencies (if not already done):
bash
npm install
Start the Backend Server:
bash
npm run dev
You should see:
code
Server is running on http://localhost:5000
3.2. Frontend Setup
Navigate to the Frontend Directory:
bash
cd ~/Documents/Code/chatgpt-react-app
Install Dependencies (if not already done):
bash
npm install
Start the Frontend Server:
bash
npm start
The application should open automatically in your default web browser at http://localhost:3000. If not, manually navigate to that URL.
4. Testing the Enhancements
4.1. Send Text Messages
Action: Type a message in the textarea and click "Send" or press Enter.
Expected Result: Your message appears on the right side (user), and the bot's response appears on the left side.
4.2. Upload and Send Images
Action: Drag and drop an image file (JPEG, PNG, GIF) into the designated area or click to select one, then send the message.
Expected Result:
Your image appears as a thumbnail in your messages.
The bot processes the image and responds accordingly.
4.3. Upload and Send PDFs
Action: Drag and drop a PDF file into the designated area or click to select one, then send the message.
Expected Result:
A link to the PDF appears in your messages with a PDF icon.
Clicking the link opens the PDF in a new tab or downloads it, depending on the browser settings.
The bot processes the PDF and responds accordingly.
4.4. Handle Unsupported File Types
Action: Attempt to upload a file with an unsupported format (e.g., .txt, .exe).
Expected Result: An error message is displayed indicating that only JPEG, PNG, GIF images and PDF files are allowed.
4.5. Test File Size Limit
Action: Attempt to upload a file larger than 10MB.
Expected Result: An error message is displayed indicating that the file size exceeds the limit.
5. Additional Recommendations
Security Considerations:
Validate Uploaded Files: Ensure that the backend securely handles and validates uploaded files to prevent malicious uploads.
Rate Limiting: Implement rate limiting to prevent abuse of the API endpoints.
Performance Improvements:
Lazy Loading: Load images and PDFs lazily to improve performance, especially for large files.
Caching: Implement caching strategies for frequently accessed resources.
Enhanced PDF Handling:
Thumbnail Previews: Generate thumbnail previews for PDFs to enhance the user experience.
Text Extraction Feedback: Inform users if a PDF has no extractable text or if processing fails.
User Authentication:
Secure Access: Implement user authentication to restrict access to authorized users.
File Management: Allow users to manage their uploaded files securely.
Deployment Considerations:
Environment Variables: Use environment variables for configuration in production environments securely.
HTTPS: Serve the application over HTTPS to ensure secure data transmission.
Conclusion
By implementing the above enhancements, your ChatGPT-like application will offer a more polished and user-friendly experience. Users can seamlessly upload and view images and PDFs within the chat, and the improved UI provides a modern and responsive interface. If you encounter any issues during implementation or have further questions, feel free to ask!