Ravi / app.py
starkbyte45896's picture
Update app.py
c0d20e2 verified
Raw History Blame Contribute Delete
4.07 kB
from flask import Flask, request, jsonify
from pymongo import MongoClient
import os
import requests
from bs4 import BeautifulSoup
import urllib.parse
app = Flask(__name__)
# πŸ” Load MongoDB Credentials
MONGO_USER = os.getenv("MONGO_USER", "Ravi") # Default "Ravi" if not set
MONGO_PASS = os.getenv("MONGO_PASS") # Password from environment variables
MONGO_CLUSTER = "ravi.btpy9.mongodb.net" # Fixed cluster name
if not MONGO_PASS:
raise ValueError("❌ MongoDB password is missing in environment variables!")
# βœ… URL-Encode Credentials
encoded_user = urllib.parse.quote_plus(MONGO_USER)
encoded_pass = urllib.parse.quote_plus(MONGO_PASS)
# πŸ”— MongoDB Connection URI
MONGO_URI = f"mongodb+srv://{encoded_user}:{encoded_pass}@{MONGO_CLUSTER}/?retryWrites=true&w=majority"
# πŸ“Œ Connect to MongoDB
try:
client = MongoClient(MONGO_URI)
db = client["Ravi"]
collection = db["qna"]
print("βœ… Connected to MongoDB successfully!")
except Exception as e:
print(f"❌ MongoDB Connection Error: {e}")
# πŸ“Œ Add a Question-Answer Pair
@app.route('/add_qna', methods=['POST'])
def add_qna():
data = request.json
question = data.get("question", "").strip().lower()
answer = data.get("answer", "").strip()
if not question or not answer:
return jsonify({"error": "Both question and answer are required"}), 400
if collection.find_one({"question": question}):
return jsonify({"error": "Question already exists"}), 409
collection.insert_one({"question": question, "answer": answer})
return jsonify({"message": "QnA added successfully!"}), 201
# πŸ“Œ Ask a Question (Retrieve Answer)
@app.route('/ask', methods=['POST'])
def ask():
data = request.json
question = data.get("question", "").strip().lower()
if not question:
return jsonify({"error": "Question is required"}), 400
result = collection.find_one({"question": question})
if result:
return jsonify({"answer": result["answer"]}) # Return stored answer
else:
return jsonify({"answer": web_scrape_answer(question)}) # Fetch from web
# πŸ“Œ List All Stored Questions & Answers
@app.route('/list_qna', methods=['GET'])
def list_qna():
qna_list = list(collection.find({}, {"_id": 0})) # Exclude MongoDB `_id`
return jsonify({"qna_list": qna_list})
# πŸ“Œ Update an Existing QnA
@app.route('/update_qna', methods=['PUT'])
def update_qna():
data = request.json
question = data.get("question", "").strip().lower()
new_answer = data.get("answer", "").strip()
if not question or not new_answer:
return jsonify({"error": "Both question and new answer are required"}), 400
result = collection.update_one({"question": question}, {"$set": {"answer": new_answer}})
if result.matched_count == 0:
return jsonify({"error": "Question not found"}), 404
return jsonify({"message": "QnA updated successfully!"})
# πŸ“Œ Delete a QnA Entry
@app.route('/delete_qna', methods=['DELETE'])
def delete_qna():
data = request.json
question = data.get("question", "").strip().lower()
if not question:
return jsonify({"error": "Question is required"}), 400
result = collection.delete_one({"question": question})
if result.deleted_count == 0:
return jsonify({"error": "Question not found"}), 404
return jsonify({"message": "QnA deleted successfully!"})
# πŸ“Œ Web Scraping Function (GeeksforGeeks)
def web_scrape_answer(question):
search_query = question.replace(" ", "+")
url = f"https://www.geeksforgeeks.org/?s={search_query}"
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
if response.status_code == 200:
soup = BeautifulSoup(response.text, "html.parser")
first_result = soup.find("div", class_="entry-content")
if first_result:
return first_result.text.strip()
return "I couldn't find an answer. Try rephrasing the question."
if __name__ == '__main__':
app.run(host="0.0.0.0", port=7860, debug=True)