File size: 3,344 Bytes
20f553c
 
 
8ee7c02
20f553c
85a850b
 
20f553c
a893632
20f553c
 
85a850b
1c8d438
 
20f553c
85a850b
a893632
 
8ee7c02
1c8d438
20f553c
85a850b
8ee7c02
 
85a850b
8ee7c02
a893632
 
 
85a850b
a893632
 
 
85a850b
20f553c
 
85a850b
 
20f553c
 
85a850b
20f553c
 
 
85a850b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c8d438
 
85a850b
 
20f553c
a893632
85a850b
20f553c
 
 
1c8d438
85a850b
20f553c
1c8d438
 
 
20f553c
1c8d438
8ee7c02
a893632
1c8d438
 
a893632
1c8d438
 
 
20f553c
85a850b
 
 
1c8d438
85a850b
 
 
 
 
 
 
 
 
 
 
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
import os
import re
import streamlit as st
from openai import OpenAI
from dotenv import load_dotenv
from docx import Document
from io import BytesIO

# Load environment variables
load_dotenv()

# Page config
st.set_page_config(page_title="🎓 Sharqi Education Chatbot", layout="wide")
st.title("🎓 Sharqi Education Chatbot")

# Check API key
groq_api_key = os.getenv("GROQ_API_KEY")
if not groq_api_key:
    st.error("❌ GROQ_API_KEY is not set in the environment variables.")
    st.stop()

# OpenAI client for GROQ
client = OpenAI(
    api_key=groq_api_key,
    base_url="https://api.groq.com/openai/v1"
)

model_name = "llama3-70b-8192"

# Session state
if "history" not in st.session_state:
    st.session_state.history = []

# Function to build chat messages
def build_messages():
    return [
        {"role": "user" if sender == "You" else "assistant", "content": msg}
        for sender, msg in st.session_state.history
    ]

# Clean model output
def clean_think_tags(text: str) -> str:
    return re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()

# Detect Urdu (rudimentary check)
def is_urdu(text: str) -> bool:
    return any("\u0600" <= char <= "\u06FF" for char in text)

# Convert text to Word and return BytesIO
def create_word_file(text):
    doc = Document()
    if is_urdu(text):
        style = doc.styles['Normal']
        font = style.font
        font.name = 'Jameel Noori Nastaleeq'
    doc.add_paragraph(text)
    buffer = BytesIO()
    doc.save(buffer)
    buffer.seek(0)
    return buffer

# Show previous chat history
for sender, message in st.session_state.history:
    with st.chat_message("user" if sender == "You" else "assistant"):
        align = "right" if is_urdu(message) else "left"
        st.markdown(f"<div style='text-align:{align}; direction:{'rtl' if align=='right' else 'ltr'};'>{message}</div>", unsafe_allow_html=True)

# Chat input
user_input = st.chat_input("اردو یا انگلش میں سوال کریں...")

if user_input:
    st.session_state.history.append(("You", user_input))
    with st.chat_message("user"):
        st.markdown(f"<div style='text-align:right;'>{user_input}</div>", unsafe_allow_html=True)

    with st.chat_message("assistant"):
        placeholder = st.empty()
        placeholder.write("⏳ Thinking...")

        try:
            response = client.chat.completions.create(
                model=model_name,
                messages=build_messages()
            )
            raw_output = response.choices[0].message.content
            reply = clean_think_tags(raw_output)
        except Exception as e:
            reply = f"❌ API Error: {e}"

        placeholder.markdown(
            f"<div style='text-align:{'right' if is_urdu(reply) else 'left'};'>{reply}</div>", unsafe_allow_html=True
        )
        st.session_state.history.append(("Bot", reply))

        # Buttons for copy & download
        with st.expander("🔧 Options"):
            st.code(reply, language="text")
            st.download_button(
                label="📄 Download Reply as Word",
                data=create_word_file(reply),
                file_name="reply.docx",
                mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            )
            st.text_input("📋 Copy this:", value=reply, key="copy_field")