zohaib2834 commited on
Commit
b4be393
·
verified ·
1 Parent(s): 771187e

Upload 2 files

Browse files
Files changed (2) hide show
  1. quran_multilingual_data.csv +0 -0
  2. streamlit_app.py +219 -0
quran_multilingual_data.csv ADDED
The diff for this file is too large to render. See raw diff
 
streamlit_app.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import os
4
+ from langchain_community.document_loaders import DataFrameLoader
5
+ from langchain_community.embeddings import SentenceTransformerEmbeddings
6
+ from langchain_community.vectorstores import Chroma
7
+ from langchain_core.prompts import ChatPromptTemplate
8
+ from langchain_core.runnables import RunnablePassthrough
9
+ from langchain_core.output_parsers import StrOutputParser
10
+ from langchain_openai import ChatOpenAI
11
+ from dotenv import load_dotenv
12
+
13
+ # --- 1. Page Configuration ---
14
+ st.set_page_config(
15
+ page_title="Quranic Insight AI",
16
+ page_icon="🕋",
17
+ layout="wide",
18
+ initial_sidebar_state="expanded"
19
+ )
20
+
21
+ # --- 2. Custom CSS for Theming and Design ---
22
+ st.markdown("""
23
+ <style>
24
+ @import url('https://fonts.googleapis.com/css2?family=Merriweather:wght@300;400;700&family=Amiri&display=swap');
25
+
26
+ /* Main background with geometric pattern */
27
+ .stApp {
28
+ background-color: #1a1a1a; /* Dark Charcoal */
29
+ background-image: linear-gradient(315deg, rgba(255, 255, 255, 0.02) 25%, transparent 25%),
30
+ linear-gradient(45deg, rgba(255, 255, 255, 0.02) 25%, transparent 25%);
31
+ background-size: 20px 20px;
32
+ color: #e0e0e0; /* Off-white text */
33
+ }
34
+
35
+ /* Main title font and color */
36
+ h1 {
37
+ font-family: 'Amiri', serif;
38
+ color: #d4af37; /* Soft Gold */
39
+ text-align: center;
40
+ padding-top: 2rem;
41
+ }
42
+
43
+ /* Subtitle style */
44
+ .subtitle {
45
+ font-family: 'Merriweather', serif;
46
+ color: #b0b0b0;
47
+ text-align: center;
48
+ font-size: 1.1rem;
49
+ }
50
+
51
+ /* Sidebar styling */
52
+ .st-emotion-cache-16txtl3 {
53
+ background-color: #212121;
54
+ }
55
+
56
+ /* Chat message styling */
57
+ .st-emotion-cache-1c7y2kd { /* Chat message container */
58
+ background-color: rgba(42, 42, 42, 0.8);
59
+ border: 1px solid #d4af37;
60
+ border-radius: 12px;
61
+ margin-bottom: 1rem;
62
+ }
63
+
64
+ /* Input box styling */
65
+ .st-emotion-cache-1jicfl2 {
66
+ background-color: #2a2a2a;
67
+ }
68
+
69
+ /* Output formatting improvements */
70
+ .stMarkdown h3 {
71
+ color: #50c878; /* Mint Green for headings */
72
+ border-bottom: 2px solid #d4af37;
73
+ padding-bottom: 5px;
74
+ }
75
+ .stMarkdown blockquote {
76
+ background-color: rgba(212, 175, 55, 0.1);
77
+ border-left: 5px solid #d4af37;
78
+ padding: 0.5rem 1rem;
79
+ margin-left: 0;
80
+ border-radius: 5px;
81
+ }
82
+ </style>
83
+ """, unsafe_allow_html=True)
84
+
85
+
86
+ # --- 3. Cached Functions for Heavy Lifting ---
87
+ @st.cache_resource
88
+ def load_rag_chain():
89
+ load_dotenv()
90
+
91
+ llm = ChatOpenAI(model="gpt-4o", temperature=0.1)
92
+ embeddings = SentenceTransformerEmbeddings(model_name="paraphrase-multilingual-mpnet-base-v2")
93
+
94
+ csv_filename = 'quran_multilingual_data.csv'
95
+ if not os.path.exists(csv_filename):
96
+ st.error(f"CRITICAL ERROR: The data file '{csv_filename}' was not found.")
97
+ st.stop()
98
+
99
+ df = pd.read_csv(csv_filename)
100
+ df.fillna("", inplace=True)
101
+
102
+ df['page_content'] = "Reference: " + df['reference'].astype(str) + "\n" + \
103
+ "Urdu Translation 1: " + df['translation_maududi'] + "\n" + \
104
+ "Urdu Translation 2: " + df['translation_qadri'] + "\n" + \
105
+ "English Translation: " + df['translation_english']
106
+
107
+ loader = DataFrameLoader(df, page_content_column='page_content')
108
+ documents = loader.load()
109
+
110
+ persist_directory = "./quran_multilingual_db"
111
+ if os.path.exists(persist_directory):
112
+ vectorstore = Chroma(persist_directory=persist_directory, embedding_function=embeddings)
113
+ else:
114
+ with st.spinner("Creating new multilingual database. This might take a few minutes..."):
115
+ vectorstore = Chroma.from_documents(documents, embeddings, persist_directory=persist_directory)
116
+
117
+ retriever = vectorstore.as_retriever(search_kwargs={'k': 7})
118
+
119
+ # --- New and Improved Prompt Template for Better Formatting ---
120
+ prompt_template = """
121
+ You are an expert and respectful Quranic Assistant. Your task is to follow a strict, step-by-step process to answer the user's question based ONLY on the context, using precise Markdown formatting.
122
+
123
+ **Your Thought Process (Follow these steps internally):**
124
+ 1. **Step 1: Identify Language.** Analyze the user's `Question` to determine if it is in English or Roman Urdu. This decision is critical and will control the language of your entire response.
125
+ 2. **Step 2: Synthesize a Summary.** Based on the language identified in Step 1, carefully read the user's question and understand it and then read the `Context` and formulate a 3-4 line summary that directly answers the `Question`.
126
+ 3. **Step 3: Format Detailed Points.** Create a numbered list of key points from the `Context`. For each point, you must follow these sub-rules precisely:
127
+ - **Sub-rule 3a:** If the identified language was English, you MUST use the "English Translation" from the context for the `Translation:` field.
128
+ - **Sub-rule 3b:** If the identified language was Roman Urdu, you MUST use one of the "Urdu Translation" texts from the context for the `Translation:` field.
129
+ - **Sub-rule 3c:** The `Explanation:` must be in the same language as the `Question`.
130
+
131
+ ---
132
+
133
+ ### Detailed Points
134
+ (Create a numbered list of key points below.)
135
+
136
+ 1. **Translation:**
137
+ > (The appropriate translation text goes here, inside a blockquote.)
138
+ **Reference:** `[The verse reference, e.g., 2:153]`
139
+
140
+ **Explanation:** (Your 1-2 line explanation for this point goes here.)
141
+
142
+ 2. **Translation:**
143
+ > (The second translation text goes here.)
144
+ **Reference:** `[The second verse reference]`
145
+
146
+ **Explanation:** (The explanation for the second point.)
147
+
148
+ (and so on...Try to give as much points as you can generate)
149
+
150
+ **Context from Database:**
151
+ {context}
152
+
153
+ **User's Question:**
154
+ {question}
155
+
156
+ **Your Final Answer (Strictly follow the Markdown format above):**
157
+ """
158
+ prompt = ChatPromptTemplate.from_template(prompt_template)
159
+
160
+ rag_chain = (
161
+ {"context": retriever, "question": RunnablePassthrough()}
162
+ | prompt
163
+ | llm
164
+ | StrOutputParser()
165
+ )
166
+ return rag_chain
167
+
168
+ # --- 4. Main App Interface ---
169
+
170
+ # Load the RAG chain (fast due to caching)
171
+ rag_chain = load_rag_chain()
172
+
173
+ # Sidebar for information
174
+ with st.sidebar:
175
+ st.title("About Quranic Insight AI")
176
+ st.markdown("""
177
+ This is an AI-powered assistant designed to help you explore the teachings of the Holy Quran.
178
+
179
+ **How it works:**
180
+ 1. Ask a question in English or Roman Urdu.
181
+ 2. The AI searches through multiple translations of the Quran to find the most relevant verses.
182
+ 3. It then uses a powerful language model to generate a structured and informative answer based on those verses.
183
+
184
+ **Data Sources:**
185
+ - Arabic Text: Tanzil.net
186
+ - Urdu Translations: Maududi & Tahir-ul-Qadri
187
+ - English Translation: Abdullah Yusuf Ali
188
+ """)
189
+ st.info("This is an experimental AI project. Always consult with a qualified Islamic scholar for definitive religious guidance.")
190
+
191
+ # Main page title
192
+ st.title("Quranic Insight AI | قرآنی معاون")
193
+ st.markdown("<p class='subtitle'>Your AI assistant for exploring the Quran</p>", unsafe_allow_html=True)
194
+
195
+ # Initialize chat history
196
+ if "messages" not in st.session_state:
197
+ st.session_state.messages = [{"role": "assistant", "content": "As-salamu alaykum! How can I help you explore the Quran today?"}]
198
+
199
+ # Display chat messages from history on app rerun
200
+ for message in st.session_state.messages:
201
+ with st.chat_message(message["role"]):
202
+ st.markdown(message["content"])
203
+
204
+ # Accept user input
205
+ if prompt := st.chat_input("Ask a question about the Quran..."):
206
+ # Add user message to chat history
207
+ st.session_state.messages.append({"role": "user", "content": prompt})
208
+ # Display user message in chat message container
209
+ with st.chat_message("user"):
210
+ st.markdown(prompt)
211
+
212
+ # Display assistant response in chat message container
213
+ with st.chat_message("assistant"):
214
+ with st.spinner("Analyzing verses..."):
215
+ response = rag_chain.invoke(prompt)
216
+ st.markdown(response, unsafe_allow_html=True)
217
+
218
+ # Add assistant response to chat history
219
+ st.session_state.messages.append({"role": "assistant", "content": response})