Spaces:
Runtime error
Runtime error
Update main.py
Browse files10 unmodified lines11121314151617181920212223241 unmodified line26272829303132333420 unmodified lines555657585960617 unmodified lines6970717273747589 unmodified lines16516616716816917053 unmodified lines22422522622722822923023123223323423523623723823924024124224324424524624724824925025122 unmodified lines274275276277278279280317 unmodified lines5985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227232 unmodified lines726727728729730731732733734735138 unmodified lines87487587687787810 unmodified linesfrom middleware.authUser import auth_userfrom datetime import timedeltafrom controllers.demo import get_initial_datafrom controllers.mindmap import saveMindmap, getMindmap, getMindmapHistory, deleteMindmap, getMindmapByid, saveMindmapByIdimport jsonfrom bson import ObjectIdfrom dotenv import load_dotenvimport osimport reimport requestsload_dotenv()1 unmodified linebcrypt = Bcrypt(app)jwt = JWTManager(app)CORS(app)app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET')# MongoDB configurationusername = urllib.parse.quote_plus(os.getenv('MONGO_USERNAME'))20 unmodified linesGOOGLE_API_KEY=os.getenv('GOOGLE_API_KEY')genai.configure(api_key=GOOGLE_API_KEY)model = genai.GenerativeModel('gemini-pro')# Caches to reduce no of queries to MongoDB...user_id_ping = {'current': 0}7 unmodified linesdef index2():return "routes checking..."#generative model routes@app.route('/tree', methods=["POST", "GET"])def tree():89 unmodified lines# return temp@app.route('/tree/demo', methods=["POST"])def treeDemo():if request.method == 'POST':data = request.get_json()53 unmodified lines# return temp@app.route('/mindmap/generate/data', methods=["POST"])def generateData():if request.method == 'POST':data = request.get_json()topic = data.get('topic')description = data.get('description')category = data.get('category')print(topic)print(description)print(category)response = model.generate_content('''I will provide you a topic. You need to generate its detailed explanation also provide its links to the related topics and subtopics and respond with html format with tailiwindcss styling, wrapped under a single<div></div>.- keep the background tranparent.- Title should be in text-2xl font-bold.- Subtitle should be in text-lg font-semibold.- make sure the content is well structured and easy to read.- make sure the link text style is in text-aqua.Topic: ''' + topic)print(response.text)json_data = response.textmodified_json_data = json_data[8:-3]return jsonify({'success': True, 'data': modified_json_data})def res(user_id):avg_text = 022 unmodified linesreturn True@app.route('/interview', methods=["POST", "GET"])def interview():if request.method == 'POST':317 unmodified linesdata = request.jsonreturn deleteMindmap(userId, data, savedMindmap)@app.route('/mindmap/demo', methods=['POST'])def mindmapDemo():data = request.jsonprint(data)return get_initial_data(), 200@app.route('/roadmap', methods=['POST'])def roadmap():if request.method == 'POST':data = request.get_json()user_id = data.get('user_id')day_data = data.get('todayData')if data.get('type') == 1:# Generate New Roadmapresponse = model.generate_content('''Generate a roadmap for Web developement in 2 months in following JSON format:[{"week1": {"title": "...","description": "What will i learn in this week...","data": {"day1": {"heading": "....","description": "What will i learn on this day...","links": ["link1","link2",....]},"day2": {"description": "...","heading": "....","links": ["link1","link2",....]},...},{"week2": {"title": "...","description": "What will i learn in this week...","data": {"day1": {"heading": "....","description": "What will i learn on this day...","links": ["link1","link2",....]},"day2": {"description": "...","heading": "....","links": ["link1","link2",....]},...continue for other weeks...]Generate topics for all 7 days in a week and reference links only links(no header) accordingly.''') # Prompt# Youtube Integration & links modificationprint(response)print(response.text)roads_data = json.loads(response.text)print(roads_data)return jsonify({'success': True})API_KEY = os.environ('YOUTUBE_API_KEY')url = "https://youtube.googleapis.com/youtube/v3/search"for index, ele in enumerate(roads_data):for i in range(0,7):params = {"part": "snippet","q": ele[f"week{index + 1}"]['data'][f"day{i+1}"]['heading'],"key": API_KEY}response = requests.get(url, params=params)if response.status_code == 200:print(response.json())video_data = response.json()temp1 = []for vid in video_data['items']:if vid['id']['kind']=='youtube#playlist':temp1.append({'viewed': False, 'type': 'playlist', 'playlistId': vid['id']['playlistId'], 'videoTitle': vid['snippet']['title'], 'channelName': vid['snippet']['channelTitle'], 'thumbnail': vid['snippet']['thumbnails']['high']['url']})elif vid['id']['kind']=='youtube#video':temp1.append({'viewed': False, 'type': 'video', 'videoId': vid['id']['videoId'], 'videoTitle': vid['snippet']['title'], 'channelName': vid['snippet']['channelTitle'], 'thumbnail': vid['snippet']['thumbnails']['high']['url']})ele[f"week{index + 1}"]['data'][f"day{i+1}"]['youtube'] = temp1# Reference Linkstemp2 = []for link in ele[f"week{index + 1}"]['data'][f"day{i+1}"]['links']:temp2.append({'link': link, 'visited': False})ele[f"week{index + 1}"]['data'][f"day{i+1}"]['links'] = temp2else:print("Error:", response.json())# Save to MongoDBroadmap_collection.insert_one({'data': roads_data, 'activeDays': [day_data], 'user_id': user_id})return jsonify({'success': True})elif data.get('type') == 2:# Get roadmap data2 unmodified linesreturn jsonify({'success': True, 'roadmapData': {'data': roadmap_data['data']}, 'activeDays': roadmap_data['activeDays']})else:return jsonify({'success': False})# return jsonify({'success': True, 'roadmapData': roads_data_demo, 'activeDays': active_days})@app.route('/roadmapmodder', methods=['POST'])def roadmapmodder():if request.method == 'POST':data = request.get_json()138 unmodified linesreturn jsonify({'success': True})if __name__ == '__main__':app.run(debug=True, host='0.0.0.0')10 unmodified lines11121314151617181920212223241 unmodified line2627282930313233343520 unmodified lines5657585960616263646566676869707172737475767778798081828384858687888990917 unmodified lines9910010110210310489 unmodified lines19419519619719819920053 unmodified lines25425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828922 unmodified lines312313314315316317317 unmodified lines6356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887892 unmodified lines792793794795796797798799800801802803804805806807808809810811812813814815816817818819820138 unmodified lines95996096196296396410 unmodified linesfrom middleware.authUser import auth_userfrom datetime import timedeltafrom controllers.demo import get_initial_datafrom controllers.mindmap import saveMindmap, getMindmap, getMindmapHistory, deleteMindmap, getMindmapByid, saveMindmapById, saveGeneratedDataimport jsonfrom bson import ObjectId, json_utilfrom dotenv import load_dotenvimport osimport reimport requestsimport timeload_dotenv()1 unmodified linebcrypt = Bcrypt(app)jwt = JWTManager(app)app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET')CORS(app,resources={r"/*":{"origins":"*"}})# MongoDB configurationusername = urllib.parse.quote_plus(os.getenv('MONGO_USERNAME'))20 unmodified linesGOOGLE_API_KEY=os.getenv('GOOGLE_API_KEY')genai.configure(api_key=GOOGLE_API_KEY)generation_config = {"temperature": 0.8,"top_p": 1,"top_k": 40,"max_output_tokens": 2048,}safety_settings = [{"category": "HARM_CATEGORY_HARASSMENT","threshold": "BLOCK_MEDIUM_AND_ABOVE"},{"category": "HARM_CATEGORY_HATE_SPEECH","threshold": "BLOCK_MEDIUM_AND_ABOVE"},{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT","threshold": "BLOCK_MEDIUM_AND_ABOVE"},{"category": "HARM_CATEGORY_DANGEROUS_CONTENT","threshold": "BLOCK_MEDIUM_AND_ABOVE"},]model = genai.GenerativeModel('gemini-1.0-pro',generation_config=generation_config,safety_settings=safety_settings)# Caches to reduce no of queries to MongoDB...user_id_ping = {'current': 0}7 unmodified linesdef index2():return "routes checking..."#generative model routes@app.route('/tree', methods=["POST", "GET"])def tree():89 unmodified lines# return temp@app.route('/tree/demo', methods=["POST"])@auth_userdef treeDemo():if request.method == 'POST':data = request.get_json()53 unmodified lines# return temp@app.route('/mindmap/generate/data', methods=["POST"])# @auth_userdef generateData():if request.method == 'POST':data = request.get_json()topic = data.get('topic')description = data.get('description')category = data.get('category')nodeId = data.get('nodeId')mapId = data.get('mapId')# userId = request.userId# try:# mindMap = savedMindmap.find_one({"_id": ObjectId(mapId)})# if mindMap["userId"] != userId:# return jsonify({"message": "Unauthorized"}), 401# except Exception as e:# print(e)# return jsonify({"error": "An error occurred"}), 500response = model.generate_content('''I will provide you a topic & related description. You need to generate its detailed explanation, also provide its links to the related topics and respond in markdown.- make sure the content is well structured and easy to read.Topic: ''' + topic + '\n\n' + '''Description: ''' + description)print(response.text)json_data = response.textsaveGeneratedData(mapId, nodeId, json_data, savedMindmap)return jsonify({'success': True, 'data': json_data})def res(user_id):avg_text = 022 unmodified linesreturn True@app.route('/interview', methods=["POST", "GET"])def interview():if request.method == 'POST':317 unmodified linesdata = request.jsonreturn deleteMindmap(userId, data, savedMindmap)@app.route('/mindmap/demo', methods=['POST'])def mindmapDemo():data = request.jsonprint(data)return get_initial_data(), 200@app.route('/roadmap', methods=['POST'])# @auth_userdef roadmap():if request.method == 'POST':data = request.get_json()user_id = data.get('user_id')if data.get('type') == 1:day_data = data.get('todayData')position = data.get('position')time_road = data.get('time')company = data.get('company')# Generate New Roadmapchat_starter = '''Generate a week-wise roadmap for '''+ position + ''' in English in the following JSON format:{"week1": {"title": "...","description": "What will i learn in this week...","data": {"day1": {"description": "...","heading": "What will I do on this day...","links": [ "link1", "link2", .... ]},"day2": {"description": "...","heading": "What will I do on this day...","links": [ "link1", "link2", .... ]},"day3": {"description": "...","heading": "What will I do on this day...","links": [ "link1", "link2", .... ]},"day4": {"description": "...","heading": "What will I do on this day...","links": [ "link1", "link2", .... ]},"day5": {"description": "...","heading": "What will I do on this day...","links": [ "link1", "link2", .... ]},"day6": {"description": "...","heading": "What will I do on this day...","links": [ "link1", "link2", .... ]},"day7": {"description": "...","heading": "What will I do on this day...","links": [ "link1", "link2", .... ]}}}}- I am preparing to get '''+ position + ''' at ''' + company + '''company.- I will ask you one by one to generate for next weeks. Generate only links, do not add anything to links.- It is required that the response should be an object. Don't include any other verbose explanations and don't include the markdown syntax anywhere.- Roadmap length is of total ''' + time_road + ''' weeks. So adjust the content among the weeks accordingly.''' # Promptroadmap_list = []chat = model.start_chat(history=[])response = chat.send_message(chat_starter)print(response.text)if response.text[0] == '{':roadmap_list.append(json.loads(response.text))elif response.text[0] == '`':roadmap_list.append(json.loads(response.text[7:-3]))for i in range(1,int(time_road)):new_response = chat.send_message(f"Now generate for next week{i+1}")print(new_response.text)if new_response.text[0] == '{':roadmap_list.append(json.loads(new_response.text))elif new_response.text[0] == '`':roadmap_list.append(json.loads(new_response.text[7:-3]))roads_data = roadmap_listprint(roads_data)time.sleep(60)# Youtube Integration & links modificationAPI_KEY = os.getenv('YOUTUBE_API_KEY')url = "https://youtube.googleapis.com/youtube/v3/search"for index, ele in enumerate(roads_data):for i in range(0,7):params = {"part": "snippet","q": ele[f"week{index + 1}"]['data'][f"day{i+1}"]['heading'] + ele[f"week{index + 1}"]['title'],"key": API_KEY,"maxResults" : 3}response = requests.get(url, params=params)if response.status_code == 200:video_data = response.json()temp1 = []for vid in video_data['items']:if vid['id']['kind']=='youtube#playlist':temp1.append({'viewed': False, 'type': 'playlist', 'playlistId': vid['id']['playlistId'], 'videoTitle': vid['snippet']['title'], 'channelName': vid['snippet']['channelTitle'], 'thumbnail': vid['snippet']['thumbnails']['high']['url']})elif vid['id']['kind']=='youtube#video':temp1.append({'viewed': False, 'type': 'video', 'videoId': vid['id']['videoId'], 'videoTitle': vid['snippet']['title'], 'channelName': vid['snippet']['channelTitle'], 'thumbnail': vid['snippet']['thumbnails']['high']['url']})ele[f"week{index + 1}"]['data'][f"day{i+1}"]['youtube'] = temp1# Reference Linkstemp2 = []for link in ele[f"week{index + 1}"]['data'][f"day{i+1}"]['links']:temp2.append({'link': link, 'visited': False})ele[f"week{index + 1}"]['data'][f"day{i+1}"]['links'] = temp2else:print("Error:", response.json())# Save to MongoDBroadmap_collection.insert_one({'data': roads_data, 'title': position, 'activeDays': [day_data], 'userId': user_id})try:results = roadmap_collection.find({"userId": user_id}, {"_id": 1, "title": 1, "activeDays": 1}).limit(5)roadmaps = [{"_id": str(result["_id"]), "title": result["title"], "activeDays": result["activeDays"]} for result in results]if roadmaps:return json_util.dumps({"data": roadmaps}), 200else:return jsonify({"msg": "No Mindmap stored"}), 404except Exception as e:print(e)return jsonify({"error": "An error occurred"}), 500# return jsonify({'success': True})elif data.get('type') == 2:# Get roadmap data2 unmodified linesreturn jsonify({'success': True, 'roadmapData': {'data': roadmap_data['data']}, 'activeDays': roadmap_data['activeDays']})else:return jsonify({'success': False})@app.route('/roadmap/history', methods=['GET'])@auth_userdef roadmapGetHistory():userId = request.userIdtry:results = roadmap_collection.find({"userId": userId}, {"_id": 1, "title": 1, "activeDays": 1}).limit(5)roadmaps = [{"_id": str(result["_id"]), "title": result["title"], "activeDays": result["activeDays"]} for result in results]if roadmaps:return json_util.dumps({"data": roadmaps}), 200else:return jsonify({"msg": "No Mindmap stored"}), 404except Exception as e:print(e)return jsonify({"error": "An error occurred"}), 500@app.route('/roadmapmodder', methods=['POST'])@auth_userdef roadmapmodder():if request.method == 'POST':data = request.get_json()138 unmodified linesreturn jsonify({'success': True})if __name__ == '__main__':app.run(debug=True, host='0.0.0.0')
main.py+198-112