Jasur05 commited on
Commit
73a796f
Β·
verified Β·
1 Parent(s): 9136ecb
Files changed (1) hide show
  1. app.py +95 -16
app.py CHANGED
@@ -76,10 +76,15 @@ def get_prompt_plain(context: str, question: str) -> str:
76
  return f"""
77
  <<START>>
78
  You are a responsible person for answering Inha University (South Korea) information. Using the context below, answer within 300 tokens.
79
- Create interactive, well-structured answers using bullet points, bold text, and proper formatting to make the information, Provide concise, answer-oriented, clear and easy to read.
80
  Do not repeat the prompt text in your output.
81
  And when context doesn't provide what user hasn't asked, don't mention it. Instead, just say in polite way you don't know it
82
  And in context text, there always will be link where this info is taken. at the end of your response, say that user can visit this link for official information. Don't forget to mention link
 
 
 
 
 
83
  Context:
84
  "{context}"
85
 
@@ -106,27 +111,100 @@ def rag_answer(question: str, collection) -> str:
106
  context = retrieve_context(question, collection, top_k=2)
107
  return generate_agent_answer(context, question)
108
 
109
- # gradio interface code below
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  def answer_question(question):
111
- """
112
- Main function that processes the question and returns the answer
113
- """
114
  if not question.strip():
115
- return "Please enter a question about Inha University."
 
 
 
 
 
 
 
 
 
 
116
 
117
- try:
118
- answer = rag_answer(question, collection)
119
- return answer
120
- except Exception as e:
121
- return f"Sorry, I encountered an error: {str(e)}"
122
 
123
- # ─── 6. Gradio Frontend ─────────────────────────────────────────────────────
124
- # Create the Gradio interface
125
  demo = gr.Interface(
126
  fn=answer_question,
127
  inputs=gr.Textbox(
128
  label="Ask me anything about Inha University SGCS…",
129
- placeholder="e.g. How many Major Required credits should I take for graduation? ",
130
  lines=2
131
  ),
132
  outputs=gr.Markdown(
@@ -134,7 +212,7 @@ demo = gr.Interface(
134
  show_copy_button=True
135
  ),
136
  title="πŸ“š Inha University SGCS Info Assistant",
137
- description="Get answers to your questions about Inha University SGCS .",
138
  theme=gr.themes.Soft(),
139
  examples=[
140
  ["What classes should I normally take as 3nd semester ISE student?"],
@@ -143,7 +221,8 @@ demo = gr.Interface(
143
  ]
144
  )
145
 
146
-
 
147
 
148
  if __name__ == "__main__":
149
  demo.launch(
 
76
  return f"""
77
  <<START>>
78
  You are a responsible person for answering Inha University (South Korea) information. Using the context below, answer within 300 tokens.
79
+ Create interactive, well-structured answers using bullet points, bold text, and proper formatting to make the information concise, answer-oriented, clear and easy to read.
80
  Do not repeat the prompt text in your output.
81
  And when context doesn't provide what user hasn't asked, don't mention it. Instead, just say in polite way you don't know it
82
  And in context text, there always will be link where this info is taken. at the end of your response, say that user can visit this link for official information. Don't forget to mention link
83
+ and at the end of response don't forget to say polite words like "have a nice day" "Have a wonderful day ""Have an awesome day" Stay awesome, or Make it a great day
84
+ Go make some magic happen
85
+ Here's to a fantastic day ahead
86
+ May your day be filled with good things
87
+ Hope something wonderful happens to you today . in general, based on question, adjust them
88
  Context:
89
  "{context}"
90
 
 
111
  context = retrieve_context(question, collection, top_k=2)
112
  return generate_agent_answer(context, question)
113
 
114
+ from datasets import Dataset, load_dataset
115
+ from huggingface_hub import HfApi
116
+ from datetime import datetime
117
+ import pandas as pd
118
+ import uuid
119
+ import os
120
+
121
+
122
+ HF_TOKEN = os.getenv("HF_TOKEN") # Set this in Space settings
123
+ DATASET_NAME = "Jasur05/inha-chat-logs"
124
+
125
+ def log_to_dataset(question, answer, response_time_ms=None):
126
+ """Log interaction to HuggingFace Dataset (permanent storage)"""
127
+ try:
128
+
129
+ new_data = {
130
+ "timestamp": [datetime.now().isoformat()],
131
+ "session_id": [str(uuid.uuid4())[:8]],
132
+ "question": [question],
133
+ "answer": [answer],
134
+ "response_time_ms": [response_time_ms or 0]
135
+ }
136
+
137
+
138
+ try:
139
+ existing_dataset = load_dataset(DATASET_NAME, split="train", token=HF_TOKEN)
140
+ existing_df = existing_dataset.to_pandas()
141
+
142
+
143
+ new_df = pd.DataFrame(new_data)
144
+ combined_df = pd.concat([existing_df, new_df], ignore_index=True)
145
+
146
+ except Exception:
147
+
148
+ combined_df = pd.DataFrame(new_data)
149
+
150
+
151
+ dataset = Dataset.from_pandas(combined_df)
152
+ dataset.push_to_hub(
153
+ DATASET_NAME,
154
+ token=HF_TOKEN,
155
+ private=True # Keep your logs private
156
+ )
157
+
158
+ print(f"βœ… Logged to dataset: {question[:50]}...")
159
+
160
+ except Exception as e:
161
+ print(f"❌ Dataset logging failed: {e}")
162
+ # Fallback to local file
163
+ log_to_local_file(question, answer, response_time_ms)
164
+
165
+ def log_to_local_file(question, answer, response_time_ms):
166
+
167
+ try:
168
+ data = {
169
+ "timestamp": datetime.now().isoformat(),
170
+ "question": question,
171
+ "answer": answer,
172
+ "response_time_ms": response_time_ms
173
+ }
174
+
175
+
176
+ df = pd.DataFrame([data])
177
+ file_exists = os.path.exists("backup_logs.csv")
178
+ df.to_csv("backup_logs.csv", mode='a', header=not file_exists, index=False)
179
+
180
+ except Exception as e:
181
+ print(f"❌ Backup logging failed: {e}")
182
+
183
  def answer_question(question):
184
+
185
+ start_time = datetime.now()
186
+
187
  if not question.strip():
188
+ answer = "Please enter a question about Inha University."
189
+ response_time_ms = 0
190
+ else:
191
+ try:
192
+ answer = rag_answer(question, collection)
193
+ response_time_ms = (datetime.now() - start_time).total_seconds() * 1000
194
+ except Exception as e:
195
+ answer = f"Sorry, I encountered an error: {str(e)}"
196
+ response_time_ms = (datetime.now() - start_time).total_seconds() * 1000
197
+
198
+ log_to_dataset(question, answer, response_time_ms)
199
 
200
+ return answer
201
+
 
 
 
202
 
 
 
203
  demo = gr.Interface(
204
  fn=answer_question,
205
  inputs=gr.Textbox(
206
  label="Ask me anything about Inha University SGCS…",
207
+ placeholder="e.g. How many Major Required credits should I take for graduation?",
208
  lines=2
209
  ),
210
  outputs=gr.Markdown(
 
212
  show_copy_button=True
213
  ),
214
  title="πŸ“š Inha University SGCS Info Assistant",
215
+ description="Get answers to your questions about Inha University SGCS.",
216
  theme=gr.themes.Soft(),
217
  examples=[
218
  ["What classes should I normally take as 3nd semester ISE student?"],
 
221
  ]
222
  )
223
 
224
+ if __name__ == "__main__":
225
+ demo.launch()
226
 
227
  if __name__ == "__main__":
228
  demo.launch(