File size: 1,781 Bytes
4492680
0b8665d
0e98666
4492680
ef1ea95
4492680
0b8665d
49c7142
4492680
6a0a4c3
 
76ad96c
4492680
0b8665d
 
fb01365
 
 
 
9f8e5a7
 
6a0a4c3
 
 
 
 
9f8e5a7
 
6a0a4c3
9f8e5a7
 
6a0a4c3
 
 
9f8e5a7
 
6a0a4c3
4bc6e3c
0e98666
396d508
 
 
 
6a0a4c3
396d508
 
120b234
31695ca
4bc6e3c
6a0a4c3
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
import os
import fitz  # PyMuPDF
import chainlit as cl
from groq import Groq

groq_client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
pdf_text = ""

@cl.on_chat_start
async def on_chat_start():
    await cl.Message(content="📄 براہ کرم PDF فائل اپلوڈ کریں یا سوال پوچھیں۔").send()

@cl.on_message
async def handle_message(message: cl.Message):
    global pdf_text

    if message.elements:
        for element in message.elements:
            if element.name.endswith(".pdf"):
                try:
                    doc = fitz.open(element.path)
                    pdf_text = ""
                    for page in doc:
                        pdf_text += page.get_text()
                    pdf_text = pdf_text[:4000]
                    await cl.Message(content="✅ PDF successfully uploaded! Now ask a question.").send()
                    return
                except Exception as e:
                    await cl.Message(content=f"❌ Error reading PDF: {e}").send()
                    return

    user_prompt = message.content.strip()
    if not user_prompt:
        await cl.Message(content="⚠️ Please ask a valid question.").send()
        return

    prompt = f"PDF Content:\n{pdf_text}\n\nQuestion: {user_prompt}" if pdf_text else user_prompt

    try:
        response = groq_client.chat.completions.create(
            model="llama3-8b-8192",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": prompt}
            ]
        )
        answer = response.choices[0].message.content.strip()
        await cl.Message(content=answer).send()
    except Exception as e:
        await cl.Message(content=f"❌ Error from LLM: {e}").send()