File size: 12,621 Bytes
d6f13c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104b883
d6f13c4
 
104b883
 
 
d6f13c4
 
104b883
d6f13c4
 
 
104b883
d6f13c4
104b883
 
d6f13c4
104b883
 
d6f13c4
104b883
d6f13c4
104b883
 
 
 
 
 
d6f13c4
 
 
104b883
 
 
 
 
 
d6f13c4
 
 
 
 
 
 
 
 
104b883
d6f13c4
 
 
104b883
d6f13c4
 
 
 
 
104b883
d6f13c4
104b883
 
 
d6f13c4
 
 
 
104b883
d6f13c4
 
 
 
104b883
d6f13c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104b883
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f13c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104b883
d6f13c4
 
 
 
 
104b883
d6f13c4
 
4b5c83f
 
d6f13c4
 
 
 
 
104b883
d6f13c4
 
 
 
 
104b883
d6f13c4
 
 
 
 
 
 
 
 
104b883
 
 
 
 
 
 
d6f13c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bfa0ff
d6f13c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104b883
d6f13c4
 
 
104b883
d6f13c4
 
 
104b883
d6f13c4
 
 
 
 
 
be5d0b2
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
"""
Gradio app for AI Project Assistant.
"""
import gradio as gr
from pathlib import Path
import os
from datetime import datetime
from dotenv import load_dotenv
from src.rag import ProjectRAG
from src.agent import ProjectAgent
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
from langchain_core.messages import SystemMessage, HumanMessage

# Load environment variables
load_dotenv()

# Global state - Initialize RAG only (not agent)
rag = None

def initialize_rag():
    """Initialize RAG system (embeddings only, no LLM needed)."""
    global rag
    data_dir = Path("./data")
    if not data_dir.exists():
        return False
    try:
        rag = ProjectRAG(data_dir)
        rag.load_and_index()
        return True
    except Exception as e:
        print(f"RAG initialization error: {e}")
        return False

# Initialize RAG on module load
initialize_rag()

def chat(message, history, project_filter, hf_token):
    """Process chat message."""
    if not hf_token or hf_token.strip() == "":
        yield "⚠️ Please enter your HuggingFace token first (get one at https://huggingface.co/settings/tokens)"
        return

    if not rag:
        yield "⚠️ System not initialized. Please check the data directory."
        return

    try:
        # Set token in environment for this request
        os.environ["HF_TOKEN"] = hf_token.strip()

        # Create agent with user's token
        agent = ProjectAgent(rag)

        # Add project context if specified
        if project_filter and project_filter != "All Projects":
            enhanced_prompt = f"[Project: {project_filter}] {message}"
        else:
            enhanced_prompt = message

        response = agent.query(enhanced_prompt)
        yield response
    except Exception as e:
        yield f"❌ Error: {str(e)}\n\nMake sure your HuggingFace token is valid."

def get_projects():
    """Get list of projects."""
    if not rag:
        return ["All Projects"]

    projects = rag.get_all_projects()
    return ["All Projects"] + projects

def structure_meeting(project_name, meeting_title, meeting_date, participants, meeting_text, hf_token):
    """Structure meeting notes using AI."""
    if not hf_token or hf_token.strip() == "":
        return "❌ Please enter your HuggingFace token first"

    if not project_name or not meeting_text:
        return "❌ Please provide both project name and meeting notes"

    try:
        # Use HF Inference API with user's token
        endpoint = HuggingFaceEndpoint(
            repo_id="meta-llama/Llama-3.2-3B-Instruct",
            temperature=0.3,
            max_new_tokens=1024,
            huggingfacehub_api_token=hf_token.strip()
        )
        llm = ChatHuggingFace(llm=endpoint)

        system_prompt = """You are a meeting notes structuring assistant.
Convert unstructured meeting notes into a well-formatted markdown document with these sections:
1. # Meeting: [title]
2. Date: [date]
3. Participants: [list]
4. ## Discussion (key points discussed)
5. ## Decisions (decisions made)
6. ## Action Items (as checkboxes with assignee and deadline if mentioned)
7. ## Blockers (any blockers or issues raised)

Format action items as:
- [ ] Person: Task description by deadline
or
- [ ] Task description (if no person/deadline mentioned)

Extract all relevant information from the raw notes."""

        user_prompt = f"""Structure these meeting notes:

Raw Notes:
{meeting_text}

Meeting Details:
- Title: {meeting_title or 'Meeting'}
- Date: {meeting_date}
- Participants: {participants or 'Not specified'}
"""

        messages = [
            SystemMessage(content=system_prompt),
            HumanMessage(content=user_prompt)
        ]

        response = llm.invoke(messages)
        structured_md = response.content

        # Save to file
        project_dir = Path("data") / project_name / "meetings"
        project_dir.mkdir(parents=True, exist_ok=True)

        filename = f"{meeting_date}-{meeting_title.lower().replace(' ', '-') if meeting_title else 'meeting'}.md"
        file_path = project_dir / filename

        with open(file_path, 'w') as f:
            f.write(structured_md)

        return f"✅ Meeting structured and saved to `{file_path}`\n\n---\n\n{structured_md}"

    except Exception as e:
        return f"❌ Error: {str(e)}"

# Create Gradio interface with custom CSS
custom_css = """
.chatbot-container {
    background-color: #f7f7f8;
    border-radius: 8px;
    padding: 10px;
}
.example-panel {
    background-color: #f0f2f6;
    border-radius: 8px;
    padding: 15px;
    height: 100%;
}
/* Mobile responsiveness */
@media (max-width: 768px) {
    .row {
        flex-direction: column !important;
    }
    .chatbot-container {
        margin-top: 10px;
    }
}
"""

with gr.Blocks(title="Sherlock: AI Project Assistant", theme=gr.themes.Soft(), css=custom_css) as demo:
    gr.Markdown("""
    # 🤖 Sherlock: AI Project Assistant

    Your intelligent assistant for managing multiple projects through meeting summaries.
    """)

    # Main tabs
    with gr.Tabs():
        # Chat tab
        with gr.Tab("💬 Chat"):
            gr.Markdown("### Ask questions about your projects")

            # HuggingFace Token input
            with gr.Row():
                hf_token_chat = gr.Textbox(
                    label="🔑 HuggingFace Token (Required)",
                    placeholder="Enter your HF token from https://huggingface.co/settings/tokens",
                    type="password",
                    scale=3
                )
                gr.Markdown("""
                **Get a free token:**
                1. Go to [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)
                2. Create a new token with "Read" permissions
                3. Paste it here
                """, scale=1)

            # Project selection dropdown
            project_dropdown = gr.Dropdown(
                label="Select Project",
                choices=get_projects(),
                value="All Projects",
                interactive=True
            )

            # Chat interface with example queries on the side
            with gr.Row(elem_classes="row"):
                # Left panel - Example queries (same width as right panel chat box)
                with gr.Column(scale=1, elem_classes="example-panel"):
                    gr.Markdown("""
                    ### 📖 How to Use
                    1. Select the project you want to query from the dropdown above
                    2. Type your question in the chat box or use one of the examples below
                    3. Press Enter or click Send

                    ### 💡 Example Queries
                    - What are the open action items?
                    - What blockers do we have?
                    - What decisions were made?
                    - What should I focus on next?
                    - Summarize the project status
                    """)

                # Right panel - Chat (same width as left panel)
                with gr.Column(scale=1, elem_classes="chatbot-container"):
                    chatbot = gr.Chatbot(
                        label="Chat",
                        height=350,
                        show_label=False
                    )

                    msg = gr.Textbox(
                        label="Your Message",
                        placeholder="What are the open action items?",
                        lines=2,
                        show_label=False
                    )

                    with gr.Row():
                        submit_btn = gr.Button("Send", variant="primary", scale=1)
                        clear_btn = gr.Button("Clear", scale=1)

            def respond(message, chat_history, project, token):
                if not message:
                    return chat_history, ""

                # Get bot response
                bot_message = ""
                for response_chunk in chat(message, chat_history, project, token):
                    bot_message = response_chunk

                # Add to history as tuple
                chat_history.append((message, bot_message))

                return chat_history, ""

            submit_btn.click(
                fn=respond,
                inputs=[msg, chatbot, project_dropdown, hf_token_chat],
                outputs=[chatbot, msg]
            )

            msg.submit(
                fn=respond,
                inputs=[msg, chatbot, project_dropdown, hf_token_chat],
                outputs=[chatbot, msg]
            )

            clear_btn.click(fn=lambda: [], outputs=chatbot)

        # Upload Meeting tab
        with gr.Tab("📤 Upload Meeting"):
            gr.Markdown("### Upload plain text meeting notes and let AI structure them")

            # HuggingFace Token input
            hf_token_upload = gr.Textbox(
                label="🔑 HuggingFace Token (Required)",
                placeholder="Enter your HF token from https://huggingface.co/settings/tokens",
                type="password"
            )

            # Project selection with toggle
            with gr.Row():
                with gr.Column():
                    project_mode = gr.Radio(
                        choices=["Use Existing Project", "Create New Project"],
                        value="Use Existing Project",
                        label="Project Selection"
                    )

                    # Existing project dropdown (shown when "Use Existing" is selected)
                    existing_project = gr.Dropdown(
                        label="Select Existing Project",
                        choices=get_projects()[1:],  # Exclude "All Projects"
                        visible=True
                    )
                    # New project textbox (shown when "Create New" is selected)
                    new_project = gr.Textbox(
                        label="New Project Name",
                        placeholder="e.g., mobile_app_redesign",
                        visible=False
                    )
                    upload_title = gr.Textbox(
                        label="Meeting Title",
                        placeholder="e.g., Sprint Planning"
                    )
                with gr.Column():
                    upload_date = gr.Textbox(
                        label="Meeting Date (YYYY-MM-DD)",
                        value=datetime.now().strftime("%Y-%m-%d"),
                        placeholder="2025-01-15"
                    )
                    upload_participants = gr.Textbox(
                        label="Participants (comma-separated)",
                        placeholder="e.g., Alice, Bob, Charlie"
                    )

            # Toggle visibility based on project mode
            def toggle_project_input(mode):
                if mode == "Use Existing Project":
                    return gr.update(visible=True), gr.update(visible=False)
                else:
                    return gr.update(visible=False), gr.update(visible=True)

            project_mode.change(
                fn=toggle_project_input,
                inputs=[project_mode],
                outputs=[existing_project, new_project]
            )

            upload_text = gr.Textbox(
                label="Meeting Notes (plain text)",
                placeholder="""Example:
We discussed the new feature requirements.
Alice will implement the login page by next Friday.
Bob raised a concern about the database migration.
We decided to use PostgreSQL instead of MySQL.
Charlie is blocked waiting for API credentials.""",
                lines=10
            )

            structure_btn = gr.Button("🤖 Structure Meeting with AI", variant="primary")
            structure_output = gr.Markdown(label="Structured Output")

            def structure_meeting_wrapper(mode, existing_proj, new_proj, title, date, participants, text, token):
                """Wrapper to handle both project modes."""
                # Determine which project name to use
                project_name = existing_proj if mode == "Use Existing Project" else new_proj
                return structure_meeting(project_name, title, date, participants, text, token)

            structure_btn.click(
                fn=structure_meeting_wrapper,
                inputs=[project_mode, existing_project, new_project, upload_title, upload_date, upload_participants, upload_text, hf_token_upload],
                outputs=structure_output
            )


# Launch
if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)