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)