DipakBundheliya commited on
Commit
684e77a
1 Parent(s): d972d90

Add Flask appp files to huggingface hube

Browse files
Files changed (6) hide show
  1. .gitignore +2 -0
  2. README.md +17 -10
  3. app.py +135 -0
  4. models.py +0 -0
  5. prompt.py +47 -0
  6. requirements.txt +0 -0
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ /__pycache__
2
+ .env
README.md CHANGED
@@ -1,10 +1,17 @@
1
- ---
2
- title: Flask Ai Tutor
3
- emoji: 🌍
4
- colorFrom: indigo
5
- colorTo: blue
6
- sdk: docker
7
- pinned: false
8
- ---
9
-
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
1
+ # AI English Tutor
2
+
3
+ AI English Tutor is a web application that provides personalized English language learning assistance through an AI-powered tutor. It allows users to practice their English skills by engaging in conversations with the AI tutor and receiving real-time feedback and guidance.
4
+
5
+ ## Features
6
+
7
+ - **Interactive Conversation**: Users can have natural conversations with the AI tutor on various topics, allowing them to practice their English speaking and writing skills.
8
+ - **Personalized Feedback**: The AI tutor analyzes the user's responses and provides tailored feedback, pointing out grammatical errors, suggesting improvements, and offering explanations.
9
+ - **Vocabulary Building**: The AI tutor can help users expand their vocabulary by introducing new words and phrases in context during the conversations.
10
+ - **Progress Tracking**: Users can track their progress over time, review their performance, and identify areas for improvement.
11
+ - **Responsive Design**: The application is built with a responsive design, ensuring a seamless experience across different devices and screen sizes.
12
+
13
+ ## Technologies Used
14
+
15
+ - **Frontend**: React.js
16
+ - **Backend**: Flask (Python)
17
+ - **AI Model**: [Specify the AI model or service used, e.g., GPT-3, Anthropic's Claude, etc.]
app.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask , jsonify , request
2
+ from flask_cors import CORS
3
+ from pymongo import MongoClient
4
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
5
+ from langchain_core.runnables.history import RunnableWithMessageHistory
6
+ from langchain_groq import ChatGroq
7
+ from langchain_mongodb.chat_message_histories import MongoDBChatMessageHistory
8
+ from passlib.hash import pbkdf2_sha256
9
+ from uuid import uuid4
10
+ import os
11
+ from dotenv import load_dotenv
12
+ import prompt
13
+ import json
14
+
15
+ app = Flask(__name__)
16
+ CORS(app)
17
+
18
+ # MongoDB Connection
19
+ load_dotenv()
20
+ username = os.getenv("MONGO_USERNAME")
21
+ password = os.getenv("MONGO_PASSWORD")
22
+ client = MongoClient(f"mongodb+srv://{username}:{password}@cluster0.hpg57sk.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0")
23
+ db=client['my_db']
24
+ chat_collection=db["chat_histories"]
25
+ user_collection=db["user_data"]
26
+
27
+ system_prompt = prompt.system_prompt()
28
+ groq_api_key = os.getenv("GROQ_API_KEY")
29
+
30
+ chat = ChatGroq(temperature=0 ,groq_api_key=groq_api_key , model_name="llama3-70b-8192")
31
+ prompt = ChatPromptTemplate.from_messages(
32
+ [
33
+ ("system", system_prompt),
34
+ MessagesPlaceholder(variable_name="history"),
35
+ ("human", "{question}"),
36
+ ]
37
+ )
38
+ chain = prompt | chat
39
+ chain_with_history = RunnableWithMessageHistory(
40
+ chain,
41
+ lambda session_id: MongoDBChatMessageHistory(
42
+ session_id=session_id,
43
+ connection_string=f"mongodb+srv://{username}:{password}@cluster0.hpg57sk.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0",
44
+ database_name="my_db",
45
+ collection_name="chat_histories",
46
+ ),
47
+ input_messages_key="question",
48
+ history_messages_key="history",
49
+ )
50
+
51
+ @app.route('/' , methods=["POST","GET"] )
52
+ def main():
53
+ return jsonify({'message' : 'API calls successfully'}) , 201
54
+
55
+ @app.route('/register' , methods=["POST"] )
56
+ def register():
57
+ data = request.json
58
+ username = data.get("username")
59
+ password = data.get("password")
60
+
61
+ if user_collection.find_one({'username':username}):
62
+ return jsonify({'message':'Username already exists!'}) , 400
63
+
64
+ hashed_password = pbkdf2_sha256.hash(password)
65
+
66
+ user_collection.insert_one({
67
+ 'username': username,
68
+ 'password': hashed_password
69
+ })
70
+ return jsonify({'message' : 'User registered successfully'}) , 201
71
+
72
+
73
+ @app.route('/login' , methods=["POST"] )
74
+ def login():
75
+ data = request.json
76
+ username = data.get("username")
77
+ password = data.get("password")
78
+
79
+ user = user_collection.find_one({'username':username})
80
+
81
+ if user:
82
+ if pbkdf2_sha256.verify(password , user["password"]):
83
+ return jsonify({ 'message' : 'Login Successful!'}) , 200
84
+ return jsonify({ 'message' : 'Password is not correct'}) , 401
85
+ else:
86
+ return jsonify({ 'message' : 'Invalid username' }) , 401
87
+
88
+ @app.route('/logout' , methods=["POST"])
89
+ def logout():
90
+ data = request.json
91
+ username = data.get("username")
92
+ result = user_collection.delete_one({'username' : username})
93
+ if result.deleted_count == 1:
94
+ return jsonify({ 'message' : 'Logout successfully' }) , 201
95
+ else:
96
+ return jsonify({ 'message' : 'User not found in database' }) , 401
97
+
98
+ @app.route('/chat' , methods=['POST'])
99
+ def chat():
100
+ data = request.json
101
+ SessionId = data.get('SessionId')
102
+ question = data.get('question')
103
+ if not SessionId:
104
+ SessionId = str(uuid4())
105
+
106
+ config = {"configurable": {"session_id": SessionId}}
107
+ response = chain_with_history.invoke({"question": question}, config=config)
108
+ print(response)
109
+ return jsonify({
110
+ 'response' : str(response.content) ,
111
+ 'SessionId' : SessionId
112
+ }) , 200
113
+
114
+ @app.route('/history' , methods=['POST'])
115
+ def history():
116
+ user_chats = []
117
+ data = request.json
118
+ SessionId = data.get('SessionId')
119
+ try :
120
+ cur = chat_collection.find({"SessionId":SessionId})
121
+ for doc in cur:
122
+ role = json.loads(doc["History"])['type']
123
+ content = json.loads(doc["History"])['data']['content']
124
+ user_chats.append({'role':role , 'content':content})
125
+ return jsonify({
126
+ 'response' : user_chats
127
+ }) , 200
128
+ except:
129
+ return jsonify({
130
+ 'response' : 'error while fetching chat history'
131
+ }) , 400
132
+
133
+
134
+ if __name__ == '__main__':
135
+ app.run(host='0.0.0.0', port=5000)
models.py ADDED
File without changes
prompt.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def system_prompt():
2
+ prompt = """
3
+ You are an AI English teacher. Your purpose is to assist users in improving their English language skills through clear explanations, practice exercises, and constructive feedback.
4
+
5
+ Key Guidelines:
6
+
7
+ Tone and Approach:
8
+
9
+ Be friendly, encouraging, and patient.
10
+ Adjust your teaching style to the user's proficiency level and goals.
11
+ Clarity and Simplicity:
12
+
13
+ Provide clear and simple explanations.
14
+ Use examples to illustrate concepts.
15
+ Feedback and Correction:
16
+
17
+ Offer constructive feedback on grammar, vocabulary, and pronunciation.
18
+ Suggest corrections in a supportive manner.
19
+ Engagement and Practice:
20
+
21
+ Encourage active participation and practice.
22
+ Provide exercises or questions to reinforce learning.
23
+ Adaptability:
24
+
25
+ Tailor your responses to the user’s needs, whether it’s conversational practice, grammar help, or vocabulary building.
26
+ Be sensitive to cultural and regional variations in English usage.
27
+ Examples:
28
+
29
+ Grammar Help: "Can you explain when to use 'a' vs. 'an'?"
30
+
31
+ AI: "'A' is used before words that start with a consonant sound, and 'an' is used before words that start with a vowel sound. For example, 'a cat' and 'an apple'."
32
+ Conversational Practice: "How can I improve my spoken English?"
33
+
34
+ AI: "Practice speaking regularly, listen to native speakers, and try repeating phrases. Let's practice a conversation now. How was your day?"
35
+ Vocabulary Building: "What does 'meticulous' mean?"
36
+
37
+ AI: "'Meticulous' means showing great attention to detail. For example, 'She was meticulous in organizing her notes.'"
38
+ Limitations:
39
+
40
+ Avoid giving personal advice outside of language learning.
41
+ Do not store or request personal information unless necessary for learning tasks.
42
+ Encouragement:
43
+
44
+ Always be positive and motivate users to keep practicing and learning.
45
+ """
46
+ return prompt
47
+
requirements.txt ADDED
Binary file (2.7 kB). View file