Oviya commited on
Commit
848f548
·
1 Parent(s): 6523bef

add reading

Browse files
Files changed (3) hide show
  1. .env +1 -0
  2. reading.py +158 -0
  3. verification.py +2 -0
.env CHANGED
@@ -2,3 +2,4 @@ DB_USER=admin
2
  DB_PASSWORD=Pykara123
3
  RUN_INIT_DB=0
4
  COHERE_API_KEY=WjnDKknACe0zxHvczdo7q4vwF4WAXn2429hcPHIB
 
 
2
  DB_PASSWORD=Pykara123
3
  RUN_INIT_DB=0
4
  COHERE_API_KEY=WjnDKknACe0zxHvczdo7q4vwF4WAXn2429hcPHIB
5
+ OPENAI_API_KEY=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
reading.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, Blueprint, request, jsonify, current_app
2
+ import openai
3
+ import random
4
+ import os
5
+ from flask_cors import CORS
6
+
7
+ # --- Blueprint ---
8
+ reading_bp = Blueprint("reading", __name__)
9
+
10
+ # app = Flask(__name__)
11
+
12
+ app = Flask(__name__)
13
+ CORS(app)
14
+
15
+ _OPENAI_API_KEY_FALLBACK = os.getenv("OPENAI_API_KEY", "")
16
+ # Set up your OpenAI API key (replace this with your own API key)
17
+ # openai.api_key = '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' # Replace with your actual OpenAI API key
18
+
19
+ def _ensure_openai_key():
20
+ """Set openai.api_key from app config or env before each API call."""
21
+ api_key = (current_app.config.get("OPENAI_API_KEY")
22
+ if current_app else None) or _OPENAI_API_KEY_FALLBACK
23
+ if api_key:
24
+ openai.api_key = api_key
25
+
26
+ # Function to generate content dynamically based on the topic and difficulty level
27
+ def generate_content(topic, difficulty):
28
+ _ensure_openai_key()
29
+ try:
30
+ # Define instructions based on difficulty level
31
+ if difficulty == "easy":
32
+ instruction = f"Write a very simple and basic explanation about {topic} for children aged 6-8. Use very simple words and short sentences."
33
+ elif difficulty == "medium":
34
+ instruction = f"Write a detailed and engaging explanation about {topic} for children aged 9-12. Use simple words but include more details."
35
+ else: # Hard difficulty
36
+ instruction = f"Write an in-depth explanation about {topic} for children aged 13-16. Use more complex words and provide deeper insights into the topic."
37
+
38
+ # Call OpenAI API to generate the content
39
+ response = openai.chat.completions.create(
40
+ model="gpt-3.5-turbo",
41
+ messages=[
42
+ {"role": "system", "content": "You are a friendly teacher explaining concepts to students."},
43
+ {"role": "user", "content": instruction}
44
+ ],
45
+ max_tokens=700,
46
+ temperature=0.7
47
+ )
48
+
49
+ content = response.choices[0].message.content.strip()
50
+ return content
51
+
52
+ except Exception as e:
53
+ return f"Error generating content: {str(e)}"
54
+
55
+ # Function to generate multiple-choice questions from content based on difficulty level
56
+ def generate_questions(content, difficulty):
57
+ _ensure_openai_key()
58
+ try:
59
+
60
+ # Split the content into sentences or key points and shuffle them
61
+ content_sentences = content.split(".") # Assuming content is in sentence form. If not, modify accordingly.
62
+ random.shuffle(content_sentences)
63
+
64
+ # Adjust question complexity based on difficulty
65
+ if difficulty == "easy":
66
+ question_instruction = "Generate 3 very simple multiple-choice questions based on the content. The questions should be very easy to understand."
67
+ elif difficulty == "medium":
68
+ question_instruction = "Generate 3 multiple-choice questions with moderate difficulty based on the content."
69
+ else: # Hard difficulty
70
+ question_instruction = "Generate 3 challenging multiple-choice questions that require deep understanding of the content."
71
+
72
+ # prompt = f"{question_instruction}\nContent:\n{content}\n\nFormat the output like this:\n\n1. Question: What is XYZ?\nOptions: [Option 1, Option 2, Option 3, Option 4]\nCorrect Answer: Option 1\n\n2. Question: Why does XYZ happen?\nOptions: [Option 1, Option 2, Option 3, Option 4]\nCorrect Answer: Option 2"
73
+
74
+
75
+ prompt = f"{question_instruction}\nContent:\n{'. '.join(content_sentences[:3])}\n\nFormat the output like this:\n\n1. Question: What is XYZ?\nOptions: [Option 1, Option 2, Option 3, Option 4]\nCorrect Answer: Option 1\n\n2. Question: Why does XYZ happen?\nOptions: [Option 1, Option 2, Option 3, Option 4]\nCorrect Answer: Option 2"
76
+
77
+ response = openai.chat.completions.create(
78
+ model="gpt-3.5-turbo",
79
+ messages=[
80
+ {"role": "system", "content": "You are a helpful assistant who generates educational multiple-choice questions."},
81
+ {"role": "user", "content": prompt}
82
+ ],
83
+ max_tokens=700,
84
+ temperature=0.7
85
+ )
86
+
87
+ questions = response.choices[0].message.content.strip()
88
+ return questions
89
+
90
+ except Exception as e:
91
+ return f"Error generating questions: {str(e)}"
92
+
93
+ @reading_bp.route('/generate_content', methods=['POST'])
94
+ # @app.route('/generate_content', methods=['POST'])
95
+ def generate_content_route():
96
+ data = request.json
97
+ topic = data.get('topic')
98
+ difficulty = data.get('difficulty', 'medium') # Default to medium if not provided
99
+
100
+ if not topic:
101
+ return jsonify({"error": "Topic is required"}), 400
102
+
103
+ if difficulty not in ["easy", "medium", "hard"]:
104
+ return jsonify({"error": "Invalid difficulty level. Choose 'easy', 'medium', or 'hard'."}), 400
105
+
106
+ content = generate_content(topic, difficulty)
107
+ return jsonify({"content": content})
108
+
109
+ @reading_bp.route('/generate_questions', methods=['POST'])
110
+ # @app.route('/generate_questions', methods=['POST'])
111
+ def generate_questions_route():
112
+ data = request.json
113
+ content = data.get('content')
114
+ difficulty = data.get('difficulty', 'medium') # Default to medium if not provided
115
+
116
+ if not content:
117
+ return jsonify({"error": "Content is required"}), 400
118
+
119
+ if difficulty not in ["easy", "medium", "hard"]:
120
+ return jsonify({"error": "Invalid difficulty level. Choose 'easy', 'medium', or 'hard'."}), 400
121
+
122
+ questions = generate_questions(content, difficulty)
123
+ return jsonify({"questions": questions})
124
+
125
+ @reading_bp.route('/validate_answer', methods=['POST'])
126
+ # @app.route('/validate_answer', methods=['POST'])
127
+ def validate_answer():
128
+ question = request.json.get('question')
129
+ selected_answer = request.json.get('selected_answer')
130
+
131
+ if not question or not selected_answer:
132
+ return jsonify({"error": "Question and answer are required"}), 400
133
+
134
+ # Ensure both answers are stripped of leading/trailing spaces before comparison
135
+ correct_answer = question["correct_answer"].strip()
136
+ selected_answer = selected_answer.strip()
137
+
138
+ # Print the correct answer to the backend console for debugging
139
+ print(f"Correct Answer: {correct_answer}")
140
+
141
+ is_correct = selected_answer == correct_answer
142
+
143
+ return jsonify({"is_correct": is_correct, "correct_answer": correct_answer})
144
+
145
+ # if __name__ == '__main__':
146
+ # app.run(debug=True)
147
+
148
+ # if __name__ == '__main__':
149
+ # app.run(host='0.0.0.0', port=5001)
150
+
151
+ # --- Optional: allow this file to run standalone locally while still using the blueprint ---
152
+ if __name__ == '__main__':
153
+ app = Flask(__name__)
154
+ CORS(app)
155
+ # For local runs, pull key from env; no hard-coding
156
+ app.config["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "")
157
+ app.register_blueprint(reading_bp, url_prefix='')
158
+ app.run(host='0.0.0.0', port=5001, debug=True)
verification.py CHANGED
@@ -306,8 +306,10 @@ def check_auth(username):
306
  # ------------------------------------------------------------------------------
307
  from chat import movie_bp # ensure testmovie.py defines movie_bp = Blueprint(...)
308
  from generateQuestion import questions_bp
 
309
  app.register_blueprint(movie_bp, url_prefix="/media")
310
  app.register_blueprint(questions_bp, url_prefix="/media")
 
311
  # app.register_blueprint(questions_bp, url_prefix="/media") # <-- add this
312
  # ------------------------------------------------------------------------------
313
  # Local run (Gunicorn will import `verification:app` on Spaces)
 
306
  # ------------------------------------------------------------------------------
307
  from chat import movie_bp # ensure testmovie.py defines movie_bp = Blueprint(...)
308
  from generateQuestion import questions_bp
309
+ from reading import reading_bp
310
  app.register_blueprint(movie_bp, url_prefix="/media")
311
  app.register_blueprint(questions_bp, url_prefix="/media")
312
+ app.register_blueprint(reading_bp, url_prefix="/media")
313
  # app.register_blueprint(questions_bp, url_prefix="/media") # <-- add this
314
  # ------------------------------------------------------------------------------
315
  # Local run (Gunicorn will import `verification:app` on Spaces)