File size: 11,215 Bytes
f5d144f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c84d14
f5d144f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fce9b68
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260

from flask import Flask, render_template_string, request, jsonify
import os
from groq import Groq
import re
from pypdf import PdfReader
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.vectorstores import Chroma
from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter

app = Flask(__name__)
app.static_folder = 'static'  

client = Groq(
    api_key="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",
)
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
vector_store = Chroma(embedding_function=embeddings, collection_name="doc_collection")
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
chat_history = []

HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat</title>
    <style>
        :root {
            --bg-gradient-start: #f0f4ff;
            --bg-gradient-end: #d9e2ff;
            --sidebar-bg: #ffffff;
            --sidebar-border: #e0e0e0;
            --text-color: #333;
            --header-color: #483d8b;
            --sidebar-h3: #6a5acd;
            --chat-bg: #ffffff;
            --user-msg-bg: #6a5acd;
            --user-msg-text: white;
            --ai-msg-bg: #f0f4ff;
            --ai-msg-text: #333;
            --input-bg: #ffffff;
            --button-bg: #6a5acd;
            --button-text: white;
            --button-hover: #483d8b;
            --thinking-color: #888;
            --shadow-color: rgba(0,0,0,0.1);
        }
        body.dark-mode {
            --bg-gradient-start: #1e1e2f;
            --bg-gradient-end: #2a2a3f;
            --sidebar-bg: #2c2c3e;
            --sidebar-border: #3a3a4e;
            --text-color: #ddd;
            --header-color: #a8a8ff;
            --sidebar-h3: #a8a8ff;
            --chat-bg: #2c2c3e;
            --user-msg-bg: #4a4a7f;
            --user-msg-text: #fff;
            --ai-msg-bg: #3a3a4e;
            --ai-msg-text: #ddd;
            --input-bg: #2c2c3e;
            --button-bg: #4a4a7f;
            --button-text: #fff;
            --button-hover: #6a6a9f;
            --thinking-color: #aaa;
            --shadow-color: rgba(0,0,0,0.3);
        }
        body { 
            margin: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
            background: linear-gradient(135deg, var(--bg-gradient-start), var(--bg-gradient-end)); 
            color: var(--text-color); display: flex; height: 100vh; 
        }
        .sidebar { 
            width: 250px; background: var(--sidebar-bg); border-right: 1px solid var(--sidebar-border); 
            padding: 20px; box-shadow: 0 2px 10px var(--shadow-color); 
            transition: width 0.3s ease; 
        }
        .sidebar:hover { width: 260px; }
        .sidebar h3 { color: var(--sidebar-h3); margin-bottom: 10px; }
        .sidebar ul { list-style: none; padding: 0; }
        .sidebar li { padding: 10px; border-radius: 8px; cursor: pointer; transition: background 0.2s; }
        .sidebar li:hover { background: rgba(255,255,255,0.1); }
        .main { flex: 1; display: flex; flex-direction: column; padding: 20px; }
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .header h1 { color: var(--header-color); font-size: 24px; }
        .logo { width: 100px; height: auto; display: block; margin: 0 auto 20px auto; } /* اندازه بزرگ‌تر و مرکزی */
        .chat-area { flex: 1; overflow-y: auto; background: var(--chat-bg); border-radius: 12px; padding: 20px; box-shadow: 0 4px 20px var(--shadow-color); }
        .message { margin-bottom: 15px; padding: 12px 18px; border-radius: 20px; max-width: 70%; }
        .user-message { background: var(--user-msg-bg); color: var(--user-msg-text); align-self: flex-end; }
        .ai-message { background: var(--ai-msg-bg); color: var(--ai-msg-text); align-self: flex-start; }
        .thinking { color: var(--thinking-color); font-style: italic; opacity: 0.7; }
        .input-area { display: flex; align-items: center; margin-top: 20px; background: var(--input-bg); border-radius: 50px; padding: 10px; box-shadow: 0 2px 10px var(--shadow-color); }
        input[type="text"] { flex: 1; border: none; padding: 12px; font-size: 16px; outline: none; background: transparent; color: var(--text-color); }
        input[type="file"] { margin-left: 10px; color: var(--text-color); }
        button { background: var(--button-bg); color: var(--button-text); border: none; padding: 10px 20px; border-radius: 50px; cursor: pointer; transition: background 0.2s; }
        button:hover { background: var(--button-hover); }
        .dark-mode-toggle { cursor: pointer; font-size: 20px; }
    </style>
</head>
<body class="dark-mode">
    <div class="sidebar">
        <img src="/static/logo.png" alt="Logo" class="logo"> 
        <h3>Chats</h3>
        <ul>
            <li>+ New Chat</li>
            <li>Today</li>
            <li>Yesterday</li>
        </ul>
    </div>
    <div class="main">
        <div class="header">
            <h1>Hi User</h1>
            <div class="dark-mode-toggle" onclick="toggleDarkMode()">☀️</div> 
        </div>
        <div class="chat-area" id="chat-area">
            <div class="message ai-message">How can I help you today?</div>
        </div>
        <div class="input-area">
            <input type="text" id="user-input" placeholder="Type your message...">
            <input type="file" id="file-upload">
            <button onclick="sendMessage()">Send</button>
        </div>
    </div>
    <script>
        function sendMessage() {
            const input = document.getElementById('user-input').value;
            const fileInput = document.getElementById('file-upload');
            const chatArea = document.getElementById('chat-area');
            
            if (input || fileInput.files.length > 0) {
                // Display user message
                const userMsg = document.createElement('div');
                userMsg.className = 'message user-message';
                userMsg.textContent = input || 'Uploaded file: ' + (fileInput.files[0]?.name || '');
                chatArea.appendChild(userMsg);
                
                // Prepare form data for upload
                const formData = new FormData();
                formData.append('message', input);
                if (fileInput.files.length > 0) {
                    formData.append('file', fileInput.files[0]);
                }
                
                // Send to backend API
                fetch('/chat', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.thinking) {
                        const thinkMsg = document.createElement('div');
                        thinkMsg.className = 'message ai-message thinking';
                        thinkMsg.textContent = data.thinking;
                        chatArea.appendChild(thinkMsg);
                    }
                    const aiMsg = document.createElement('div');
                    aiMsg.className = 'message ai-message';
                    aiMsg.textContent = data.response;
                    chatArea.appendChild(aiMsg);
                    chatArea.scrollTop = chatArea.scrollHeight;
                });
                
                document.getElementById('user-input').value = '';
                fileInput.value = '';
            }
        }

        // Add Enter key listener
        document.getElementById('user-input').addEventListener('keydown', function(event) {
            if (event.key === 'Enter') {
                event.preventDefault();
                sendMessage();
            }
        });

        // Dark mode toggle function
        function toggleDarkMode() {
            document.body.classList.toggle('dark-mode');
            const toggle = document.querySelector('.dark-mode-toggle');
            toggle.textContent = document.body.classList.contains('dark-mode') ? '☀️' : '🌙';
        }
    </script>
</body>
</html>
"""

@app.route('/')
def index():
    return render_template_string(HTML_TEMPLATE)

def process_file(file_obj):
    if not file_obj:
        return None
    file_path = file_obj.filename  
    file_extension = os.path.splitext(file_path)[1].lower()
    try:
        if file_extension == ".pdf":
            reader = PdfReader(file_obj)
            file_text = "\n".join(page.extract_text() or "" for page in reader.pages)
        elif file_extension == ".txt":
            file_text = file_obj.read().decode('utf-8')
        else:
            raise ValueError(f"Unsupported file format: {file_extension}")
        
        file_docs = [Document(page_content=file_text, metadata={"source": "uploaded_file"})]
        file_splits = text_splitter.split_documents(file_docs)
        vector_store.add_documents(file_splits)
        return file_text
    except Exception as e:
        raise RuntimeError(f"Error processing file: {str(e)}")

@app.route('/chat', methods=['POST'])
def chat():
    user_message = request.form.get('message', '')
    uploaded_file = request.files.get('file')
    
    system_prompt = "You are an AI assistant developed by Holding Khalij Fars, tasked with responding to user queries accurately and helpfully And youre default language for answering is Farsi unless user wnts you to asnwe rin another language."
        
    messages = [{"role": "system", "content": system_prompt}]
    model = "qwen/qwen3-32b"
    relevant_content = ""
    
    if uploaded_file:
        try:
            file_text = process_file(uploaded_file)
            if file_text:
                search_query = user_message
                retrieved_docs = vector_store.similarity_search(search_query, k=3)
                relevant_content = "\n".join(doc.page_content for doc in retrieved_docs)
            
            if relevant_content:
                user_message += f"\nRelevant document content: {relevant_content}"
            messages.append({"role": "user", "content": user_message})
        except Exception as e:
            messages.append({"role": "user", "content": f"Error processing file: {str(e)}. {user_message}"})
    else:
        messages.append({"role": "user", "content": user_message})
    
    try:
        chat_completion = client.chat.completions.create(
            messages=messages,
            model=model,
        )
        ai_response = chat_completion.choices[0].message.content
        
        think_parts = re.findall(r'<think>(.*?)</think>', ai_response, re.DOTALL)
        thinking = '\n'.join(think_parts).strip() if think_parts else ''
        final_response = re.sub(r'<think>.*?</think>', '', ai_response, flags=re.DOTALL).strip()
    except Exception as e:
        thinking = ''
        final_response = ''
    
    return jsonify({'thinking': thinking, 'response': final_response})

if __name__ == '__main__':
    app.run(debug=True , port=7860 , host='0.0.0.0')