Rathapoom commited on
Commit
4c5cb00
·
verified ·
1 Parent(s): 430ea28

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -33
app.py CHANGED
@@ -1,68 +1,54 @@
1
  import streamlit as st
2
  import openai
 
3
  import time
4
  import gspread
5
  from oauth2client.service_account import ServiceAccountCredentials
6
 
7
- # ตั้งค่า Google Sheets API
 
 
 
8
  scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
9
- creds = ServiceAccountCredentials.from_json_keyfile_name("genexam-2c8c645ecc0d.json", scope) # เปลี่ยนเป็นชื่อไฟล์ JSON ของคุณ
10
  client_gs = gspread.authorize(creds)
 
11
 
12
- # เปิด Google Sheets โดยใช้ชื่อของ sheet
13
- sheet = client_gs.open("GeneXam user").sheet1 # ใส่ชื่อจริงของ Google Sheet
14
-
15
- # ฟังก์ชันตรวจสอบ username ใน Google Sheets
16
  def check_user_in_sheet(username):
17
  try:
18
- users_list = sheet.col_values(1) # สมมติว่า usernames อยู่ในคอลัมน์แรก
19
  if username in users_list:
20
  return True
21
- else:
22
- return False
23
  except Exception as e:
24
  st.error(f"Error checking user: {str(e)}")
25
  return False
26
 
27
- # ฟังก์ชันอัปเดตการใช้ API ของผู้ใช้
28
  def update_api_usage(username):
29
  try:
30
  users_list = sheet.col_values(1)
31
- row_number = users_list.index(username) + 1 # หาตำแหน่งของ user
32
- api_usage = int(sheet.cell(row_number, 2).value) # คอลัมน์ที่ 2 เป็นจำนวนการใช้ API
33
  api_usage += 1
34
  sheet.update_cell(row_number, 2, api_usage)
35
  except Exception as e:
36
  st.error(f"Error updating API usage: {str(e)}")
37
 
38
- # รีเซ็ตการใช้ API เมื่อถึงเวลารีเซ็ตทุกวัน (ถ้าจำเป็น)
39
- def reset_api_usage_daily():
40
- try:
41
- users_list = sheet.col_values(1)
42
- for i, user in enumerate(users_list):
43
- sheet.update_cell(i + 1, 2, 0) # รีเซ็ตคอลัมน์ที่ 2 (การใช้ API) เป็น 0
44
- except Exception as e:
45
- st.error(f"Error resetting API usage: {str(e)}")
46
-
47
- # ตั้งค่า OpenAI API key จาก Hugging Face Secrets
48
- openai.api_key = st.secrets["OPENAI_API_KEY"]
49
-
50
- # ฟังก์ชันการสร้างข้อสอบโดยใช้ OpenAI API และมี retry logic
51
  def generate_questions_with_retry(knowledge_material, question_type, cognitive_level, extra_instructions, case_based, num_choices=None, max_retries=3):
52
- # Adjust the number of questions based on the type
53
  if question_type == "Multiple Choice":
54
  num_questions = 3
55
  elif question_type == "Fill in the Blank":
56
  num_questions = 10
57
  elif question_type == "True/False":
58
- num_questions = 5 # Generate 5 true/false questions
59
  else: # Open-ended
60
  num_questions = 3
61
 
62
  # Base prompt
63
  prompt = f"Generate {num_questions} {question_type.lower()} exam questions based on {cognitive_level.lower()} level from the following material: {knowledge_material}. {extra_instructions}"
64
 
65
- # If case-based medical situation is selected, modify the prompt
66
  if case_based:
67
  prompt = f"Generate {num_questions} {question_type.lower()} exam questions based on {cognitive_level.lower()} level from the following medical material: {knowledge_material}. The questions should be based on case-based medical situations, such as patient scenarios. {extra_instructions}"
68
  if question_type != "Fill in the Blank":
@@ -78,20 +64,20 @@ def generate_questions_with_retry(knowledge_material, question_type, cognitive_l
78
  retries = 0
79
  while retries < max_retries:
80
  try:
81
- response = openai.ChatCompletion.create(
82
- model="gpt-4o-mini",
83
  messages=[
84
  {"role": "system", "content": "You are a helpful assistant for generating exam questions."},
85
  {"role": "user", "content": prompt}
86
  ]
87
  )
88
  return response.choices[0].message.content
89
- except openai.APIConnectionError:
90
  retries += 1
91
- time.sleep(2) # Wait for 2 seconds before retrying
92
  if retries == max_retries:
93
- st.error("Failed to connect to OpenAI API after several attempts.")
94
  return None
 
95
 
96
  # ระบบ login
97
  if 'username' not in st.session_state:
 
1
  import streamlit as st
2
  import openai
3
+ from openai import OpenAI
4
  import time
5
  import gspread
6
  from oauth2client.service_account import ServiceAccountCredentials
7
 
8
+ # Set up OpenAI client
9
+ client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
10
+
11
+ # Google Sheets setup remains the same
12
  scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
13
+ creds = ServiceAccountCredentials.from_json_keyfile_name("genexam-2c8c645ecc0d.json", scope)
14
  client_gs = gspread.authorize(creds)
15
+ sheet = client_gs.open("GeneXam user").sheet1
16
 
 
 
 
 
17
  def check_user_in_sheet(username):
18
  try:
19
+ users_list = sheet.col_values(1)
20
  if username in users_list:
21
  return True
22
+ return False
 
23
  except Exception as e:
24
  st.error(f"Error checking user: {str(e)}")
25
  return False
26
 
 
27
  def update_api_usage(username):
28
  try:
29
  users_list = sheet.col_values(1)
30
+ row_number = users_list.index(username) + 1
31
+ api_usage = int(sheet.cell(row_number, 2).value)
32
  api_usage += 1
33
  sheet.update_cell(row_number, 2, api_usage)
34
  except Exception as e:
35
  st.error(f"Error updating API usage: {str(e)}")
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def generate_questions_with_retry(knowledge_material, question_type, cognitive_level, extra_instructions, case_based, num_choices=None, max_retries=3):
38
+ # Adjust number of questions based on type
39
  if question_type == "Multiple Choice":
40
  num_questions = 3
41
  elif question_type == "Fill in the Blank":
42
  num_questions = 10
43
  elif question_type == "True/False":
44
+ num_questions = 5
45
  else: # Open-ended
46
  num_questions = 3
47
 
48
  # Base prompt
49
  prompt = f"Generate {num_questions} {question_type.lower()} exam questions based on {cognitive_level.lower()} level from the following material: {knowledge_material}. {extra_instructions}"
50
 
51
+ # Modify prompt for case-based medical situations
52
  if case_based:
53
  prompt = f"Generate {num_questions} {question_type.lower()} exam questions based on {cognitive_level.lower()} level from the following medical material: {knowledge_material}. The questions should be based on case-based medical situations, such as patient scenarios. {extra_instructions}"
54
  if question_type != "Fill in the Blank":
 
64
  retries = 0
65
  while retries < max_retries:
66
  try:
67
+ response = client.chat.completions.create(
68
+ model="GPT-4o mini", # or your preferred model
69
  messages=[
70
  {"role": "system", "content": "You are a helpful assistant for generating exam questions."},
71
  {"role": "user", "content": prompt}
72
  ]
73
  )
74
  return response.choices[0].message.content
75
+ except Exception as e:
76
  retries += 1
 
77
  if retries == max_retries:
78
+ st.error(f"Failed to generate questions after {max_retries} attempts. Error: {str(e)}")
79
  return None
80
+ time.sleep(2) # Wait before retrying
81
 
82
  # ระบบ login
83
  if 'username' not in st.session_state: