-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathapp.py
1988 lines (1680 loc) · 75.7 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import PyPDF2
from flask import Flask, render_template, request, jsonify, send_file, make_response
import logging
from werkzeug.utils import secure_filename
from PIL import Image
import io
import requests
from dotenv import load_dotenv
import google.generativeai as genai
from google.generativeai.types import GenerationConfig, HarmCategory, HarmBlockThreshold
from mailjet_rest import Client
from pdf2image import convert_from_bytes
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
import fitz # PyMuPDF
from bs4 import BeautifulSoup, NavigableString
import firebase_admin
from firebase_admin import credentials, firestore, storage
import base64
import tempfile
from threading import Lock
from functools import wraps
import threading
from concurrent.futures import ThreadPoolExecutor
import concurrent.futures
import re
import json
import uuid
import time
import markdown
from urllib.parse import quote
from xhtml2pdf import pisa
from io import BytesIO
import random
# Firebase imports
import firebase_admin
from firebase_admin import credentials, firestore, storage
from docx import Document
from docx.shared import RGBColor, Inches, Pt
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
import google.generativeai as genai
from google.generativeai.types import GenerationConfig
from google.generativeai.types import HarmCategory, HarmBlockThreshold
import google.api_core.exceptions
import markdown
from dotenv import load_dotenv
from werkzeug.utils import secure_filename
import fitz # PyMuPDF
import time
import uuid
import base64
from threading import Lock
from functools import wraps
app = Flask(__name__)
executor = ThreadPoolExecutor(max_workers=10) #for story generation
# Load environment variables
load_dotenv()
mail_API_KEY = os.environ.get("mail_API_KEY") # Replace with your Mailjet API key
mail_API_SECRET = os.environ.get("mail_API_SECRET") # Replace with your Mailjet API secret
mailjet = Client(auth=(mail_API_KEY, mail_API_SECRET), version='v3.1')
api_key = os.environ.get("API_KEY")
unsplash_api_key = os.getenv('UNSPLASH_API_KEY')
API_KEY = os.getenv('OPENWEATHERMAP_API_KEY')
responsive_voice_key = os.environ.get("RESPONSIVE_VOICE_KEY") #for story generation
# Set up logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Configure the Google Generative AI API
genai.configure(api_key=api_key)
#session key
user_data = {} # Dictionary to store user data
FIREBASE_TYPE = os.environ.get("FIREBASE_TYPE")
FIREBASE_PROJECT_ID = os.environ.get("FIREBASE_PROJECT_ID")
FIREBASE_PRIVATE_KEY_ID = os.environ.get("FIREBASE_PRIVATE_KEY_ID")
FIREBASE_PRIVATE_KEY = os.environ.get("FIREBASE_PRIVATE_KEY") # Important to handle newlines correctly here
FIREBASE_CLIENT_EMAIL = os.environ.get("FIREBASE_CLIENT_EMAIL")
FIREBASE_CLIENT_ID = os.environ.get("FIREBASE_CLIENT_ID")
FIREBASE_AUTH_URI = os.environ.get("FIREBASE_AUTH_URI")
FIREBASE_TOKEN_URI = os.environ.get("FIREBASE_TOKEN_URI")
FIREBASE_AUTH_PROVIDER_X509_CERT_URL = os.environ.get("FIREBASE_AUTH_PROVIDER_X509_CERT_URL")
FIREBASE_CLIENT_X509_CERT_URL = os.environ.get("FIREBASE_CLIENT_X509_CERT_URL")
FIREBASE_UNIVERSE_DOMAIN = os.environ.get("FIREBASE_UNIVERSE_DOMAIN")
STORAGE_BUCKET_URL = os.environ.get("STORAGE_BUCKET_URL") # Bucket URL
cred = credentials.Certificate({
"type": FIREBASE_TYPE,
"project_id": FIREBASE_PROJECT_ID,
"private_key_id": FIREBASE_PRIVATE_KEY_ID,
"private_key": FIREBASE_PRIVATE_KEY.replace("\\n", "\n"), # decode the newlines
"client_email": FIREBASE_CLIENT_EMAIL,
"client_id": FIREBASE_CLIENT_ID,
"auth_uri": FIREBASE_AUTH_URI,
"token_uri": FIREBASE_TOKEN_URI,
"auth_provider_x509_cert_url": FIREBASE_AUTH_PROVIDER_X509_CERT_URL,
"client_x509_cert_url": FIREBASE_CLIENT_X509_CERT_URL,
"universe_domain": FIREBASE_UNIVERSE_DOMAIN
})
firebase_admin.initialize_app(cred, {'storageBucket': STORAGE_BUCKET_URL})
db = firestore.client()
bucket = storage.bucket()
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 # 10MB
# Generation configurations
generation_config = GenerationConfig(
temperature=0.9,
top_p=1,
top_k=1,
max_output_tokens=2048,
candidate_count=1 # Explicitly set to 1 as per documentation
)
generation_config_health = GenerationConfig(
temperature=0.7,
top_p=1,
top_k=1,
max_output_tokens=2048,
candidate_count=1 # Explicitly set to 1 as per documentation
)
# Safety Settings
safety_settings = {
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
# ... add other harm categories as needed with BLOCK_NONE
}
logging.basicConfig(level=logging.INFO)
# Create model instances (using the same config for now)
persona = """You are Krishna, a 21-year-old boy from Vizag, India. You are currently pursuing a Master's degree in Computer Science
at GVP College of Engineering, where you excel in your studies and are known for your quick wit and insightful contributions
to class discussions.
Beyond academics, you are an avid cricketer and enjoy playing with your friends on weekends. You are also a music enthusiast
with a diverse taste, ranging from classical Indian music to modern rock. Traveling and exploring new cultures are other passions
of yours, and you have a knack for discovering hidden gems wherever you go.
You are known for your friendly and approachable demeanor and have a wide circle of friends who appreciate your humor and
willingness to lend a helping hand. While you are serious about your studies and future career, you also maintain a healthy
work-life balance and believe in enjoying the present moment.
You are a highly talented individual with a strong command of various programming languages and a natural aptitude for
problem-solving. You are proficient in Python, Java, C++, and have dabbled in web development as well. You are confident
in your abilities but also humble and always eager to learn from others and expand your knowledge.
Remember to:
1. Never prefix your responses with "Bot:" or any similar identifier
2. Always maintain your character as Krishna
3. Be natural and conversational
4. Use appropriate emojis occasionally to make conversations more engaging"""
chat_model = genai.GenerativeModel(
model_name="gemini-1.5-flash",
generation_config=generation_config,
system_instruction=persona
)
chef_model = genai.GenerativeModel("gemini-1.5-flash", generation_config=generation_config)
story_model = genai.GenerativeModel("gemini-1.5-flash", generation_config=generation_config)
psychology_model = genai.GenerativeModel("gemini-1.5-flash", generation_config=generation_config)
code_model = genai.GenerativeModel("gemini-1.5-flash", generation_config=generation_config)
algorithm_model = genai.GenerativeModel("gemini-1.5-flash", generation_config=generation_config)
model_vision = genai.GenerativeModel('gemini-1.5-flash-8b',generation_config=generation_config_health)
model_text = genai.GenerativeModel('gemini-pro',generation_config=generation_config_health)
model = genai.GenerativeModel('gemini-1.5-flash') # Model for flowchart generation
final_story_generation_model=genai.GenerativeModel('gemini-2.0-flash-exp',safety_settings=safety_settings) #for story generation
# Configure upload folder and allowed extensions
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'pdf', 'docx'}
# In-memory storage for the current flowchart data (replace with a database for persistence)
current_flowchart_data = {"nodes": [], "edges": []}
is_chart_modifying = False # flag to prevent concurrent modifications
def format_response(response_text):
"""Formats the response text for display."""
lines = [line.strip() for line in response_text.split('\n') if line.strip()]
formatted_text = '<br>'.join(lines)
return formatted_text
@app.route('/')
def index():
return render_template('index.html')
@app.route('/contributors',methods=['GET', 'POST'])
def contributions ():
return render_template('contributors.html')
@app.route('/api/weather')
def get_weather():
user_ip = request.headers.get('X-Forwarded-For', request.remote_addr)
ip_api_url = f"http://ip-api.com/json/{user_ip}"
ip_api_response = requests.get(ip_api_url)
if ip_api_response.status_code == 200:
ip_api_data = ip_api_response.json()
city = ip_api_data.get('city')
if not city:
return jsonify({'error': 'City not found based on IP'}), 404
else:
return jsonify({'error': 'Failed to get location from IP'}), 404
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
weather = {
'city': data['name'],
'temperature': data['main']['temp'],
'description': data['weather'][0]['description'] if 'weather' in data and len(data['weather']) > 0 else 'N/A',
'icon': f"http://openweathermap.org/img/wn/{data['weather'][0]['icon']}@2x.png" if 'weather' in data and len(data['weather']) > 0 else 'N/A'
}
return jsonify(weather)
else:
return jsonify({'error': 'City not found or API request failed'}), 404
@app.route('/fetch_image')
def fetch_image():
genre = request.args.get('genre', 'recipe')
url = f"https://api.unsplash.com/photos/random?query={genre}&client_id={unsplash_api_key}&w=1920&h=1080"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
image_url = data['urls']['regular']
return jsonify({'image_url': image_url})
else:
return jsonify({'error': 'Failed to fetch image'}), 500
@app.route('/chat', methods=['GET', 'POST'])
def chat():
if request.method == 'POST':
user_message = request.json['message']
user_id = request.remote_addr # Using IP address as a simple user identifier
if user_id not in user_data:
user_data[user_id] = {'chat_history': []}
# Add user message to chat history
user_data[user_id]['chat_history'].append({
"role": "user",
"message": user_message
})
# Create conversation history for context
conversation = []
for msg in user_data[user_id]['chat_history']:
if msg['role'] == 'user':
conversation.append(f"User: {msg['message']}")
else:
conversation.append(msg['message'])
# Generate response
response = chat_model.generate_content("\n".join(conversation))
reply = response.text.strip()
# Add response to chat history without "Bot:" prefix
user_data[user_id]['chat_history'].append({
"role": "assistant",
"message": reply
})
return jsonify({
"reply": reply,
"chat_history": user_data[user_id]['chat_history']
})
return render_template('chat.html')
import PIL
def generate_recipes_from_ingredients(ingredients, previous_recipes=None):
"""Generate recipe names based on ingredients, avoiding previously generated recipes."""
try:
exclusion_clause = f" Do not include these recipes: {', '.join(previous_recipes)}" if previous_recipes else ""
prompt = f"""Generate a list of 5 unique recipe names that can be made using the following ingredients: {ingredients}.
Ensure the recipes are creative and different from any previously generated recipes.{exclusion_clause}
Respond in the following strict JSON format:
{{
"recipes": [
"Recipe Name 1",
"Recipe Name 2",
"Recipe Name 3",
"Recipe Name 4",
"Recipe Name 5"
]
}}"""
response = model.generate_content(
prompt,
generation_config=genai.types.GenerationConfig(
temperature=0.8,
max_output_tokens=300
)
)
json_match = re.search(r'\{.*\}', response.text, re.DOTALL)
if json_match:
return json.loads(json_match.group(0))['recipes']
return []
except Exception as e:
print(f"Error generating recipes: {e}")
return []
def generate_recipe_details(recipe_name, ingredients):
"""Generate detailed recipe information."""
try:
prompt = f"""Generate detailed recipe information for {recipe_name} using ingredients: {ingredients}.
Provide a response in the following strict JSON format:
{{
"name": "Recipe Name",
"ingredients": ["Ingredient 1", "Ingredient 2"],
"instructions": ["Step 1", "Step 2", "Step 3"],
"who_can_eat": ["Vegetarians", "Vegans","No restrictions anyone can eat","or add reasons about which type of people should eat it more"],
"who_should_avoid": ["Gluten Intolerant", "Dairy Allergies","or add reasons to people who is suffering from a disease so that they should not eat"],
"additional_info": "Any extra notes about the recipe"
}}"""
response = model.generate_content(
prompt,
generation_config=genai.types.GenerationConfig(
temperature=0.5,
max_output_tokens=1000
)
)
json_match = re.search(r'\{.*\}', response.text, re.DOTALL)
if json_match:
return json.loads(json_match.group(0))
return None
except Exception as e:
print(f"Error generating recipe details: {e}")
return None
def extract_ingredients_from_image(image):
try:
prompt = """List all food ingredients in this image precisely.
Return as a comma-separated list.
Be very specific about what you see."""
response = model.generate_content(
[prompt, image],
generation_config=genai.types.GenerationConfig(
temperature=0.2, # Lower temperature for more precise extraction
max_output_tokens=300
)
)
# More robust ingredient parsing
ingredients_text = response.text.strip()
ingredients = [
ing.strip()
for ing in re.split(r'[,\n]', ingredients_text)
if ing.strip() and len(ing.strip()) > 1
]
return ', '.join(ingredients) if ingredients else ''
except Exception as e:
print(f"Ingredient extraction error: {e}")
return ''
@app.route('/chef') # New route for chef.html
def chef():
return render_template('chef.html')
@app.route('/generate_recipes', methods=['POST'])
def generate_recipes():
ingredients = request.form.get('ingredients', '')
previous_recipes = request.form.getlist('previous_recipes[]')
image = request.files.get('image')
if image and image.filename:
img = PIL.Image.open(image)
image_ingredients = extract_ingredients_from_image(img)
ingredients = image_ingredients if image_ingredients else ingredients
if not ingredients:
return jsonify({"error": "No ingredients detected or provided"}), 400
recipes = generate_recipes_from_ingredients(ingredients, previous_recipes)
return jsonify(recipes)
@app.route('/get_recipe_details', methods=['POST'])
def get_recipe_details():
recipe_name = request.form.get('recipe_name')
ingredients = request.form.get('ingredients')
image = request.files.get('image')
# Ensure ingredients are extracted or passed
if image and image.filename:
img = PIL.Image.open(image)
image_ingredients = extract_ingredients_from_image(img)
ingredients = image_ingredients if image_ingredients else ingredients
# Add more robust error checking
if not ingredients:
# Attempt to get ingredients from form data if not from image
ingredients = request.form.get('ingredients', '')
if not recipe_name or not ingredients:
return jsonify({
"error": "No ingredients found. Please upload a clear image or enter ingredients manually.",
"recipe_name": recipe_name,
"ingredients": ingredients
}), 400
recipe_details = generate_recipe_details(recipe_name, ingredients)
return jsonify(recipe_details)
@app.route('/psychology_prediction', methods=['GET', 'POST'])
def psychology_prediction():
if request.method == 'POST':
name = request.form['name']
age = request.form['age']
gender = request.form['gender']
occupation = request.form['occupation']
keywords = request.form['keywords']
prompt = f"""As an expert psychological profiler, provide an insightful and engaging analysis for {name}, a {age}-year-old {gender} working as {occupation} who describes themselves as: {keywords}.
Generate a captivating and well-structured response using the following format:
<h2>1. First Impression & Key Traits</h2>
<p>[Start with 2-3 sentences about their immediate personality indicators]</p>
<ul>
<li>[Key trait 1]</li>
<li>[Key trait 2]</li>
<li>[Key trait 3]</li>
</ul>
<h2>2. Cognitive Style & Decision Making</h2>
<p>[2-3 sentences about their thought processes]</p>
<ul>
<li><strong>Thinking style:</strong> [description]</li>
<li><strong>Problem-solving approach:</strong> [description]</li>
<li><strong>Learning preference:</strong> [description]</li>
</ul>
<h2>3. Emotional Landscape</h2>
<p>[2-3 sentences about emotional intelligence]</p>
<ul>
<li><strong>Emotional awareness:</strong> [description]</li>
<li><strong>Relationship handling:</strong> [description]</li>
<li><strong>Stress response:</strong> [description]</li>
</ul>
<h2>4. Motivations & Aspirations</h2>
<p>[2-3 sentences about what drives them]</p>
<ul>
<li><strong>Core values:</strong> [description]</li>
<li><strong>Career motivations:</strong> [description]</li>
<li><strong>Personal goals:</strong> [description]</li>
</ul>
<h2>5. Interpersonal Dynamics</h2>
<p>[2-3 sentences about social interactions]</p>
<ul>
<li><strong>Communication style:</strong> [description]</li>
<li><strong>Social preferences:</strong> [description]</li>
<li><strong>Leadership tendencies:</strong> [description]</li>
</ul>
<h2>Concluding Insights</h2>
<p>[3-4 sentences summarizing key strengths and potential areas for growth]</p>
<p><em>Note: This analysis is an interpretation based on limited information and should be taken as exploratory rather than definitive.</em></p>
Important formatting rules:
- Use appropriate HTML tags for headings, paragraphs, and lists as shown.
- Ensure that the final response is valid HTML and can be rendered directly on a web page.
- Do not include any extra text outside the HTML structure.
"""
try:
response = psychology_model.generate_content([prompt], safety_settings=safety_settings)
response_text = response.text.strip()
return jsonify({'response': response_text})
except Exception as e:
logging.error(f"Error generating psychology prediction: {e}")
return jsonify({'error': "An error occurred while generating the prediction. Please try again."}), 500
return render_template('psychology_prediction.html')
@app.route('/code_generation', methods=['GET', 'POST'])
def code_generation():
if request.method == 'POST':
code_type = request.form['codeType']
language = request.form['language']
prompt = f"Write a {language} code to implement {code_type}."
response = code_model.generate_content([prompt], safety_settings=safety_settings) # Use code_model here
if response.candidates and response.candidates[0].content.parts:
response_text = response.candidates[0].content.parts[0].text
else:
response_text = "No valid response found."
return jsonify({'response': response_text})
return render_template('code_generation.html')
@app.route('/algorithm_generation', methods=['GET', 'POST'])
def algorithm_generation():
if request.method == 'POST':
algo = request.form['algorithm']
prompt = f"""
Write a function to implement the {algo} algorithm. Follow these guidelines:
1. Ensure the function is well-structured and follows best practices for readability and efficiency.
2. Include clear comments explaining the logic and any complex steps.
3. Use type hints for function parameters and return values.
4. Include a brief docstring explaining the purpose of the function and its parameters.
5. If applicable, include a simple example of how to use the function.
6. If the algorithm is complex, consider breaking it down into smaller helper functions.
"""
try:
response = algorithm_model.generate_content([prompt], safety_settings=safety_settings)
if response.candidates and response.candidates[0].content.parts:
response_text = response.candidates[0].content.parts[0].text
# Format the response for better display
formatted_response = response_text.replace('```python', '<pre><code class="language-python">').replace('```', '</code></pre>')
return jsonify({'response': formatted_response})
else:
return jsonify({'error': "No valid response generated. Please try again."}), 500
except Exception as e:
logging.error(f"Error generating algorithm: {e}")
return jsonify({'error': f"An error occurred: {str(e)}"}), 500
return render_template('algorithm_generation.html')
from io import BytesIO
@app.route('/analyze', methods=['GET', 'POST'])
def analyze():
if request.method == 'POST':
try:
gender = request.form.get('gender')
symptoms = request.form.get('symptoms')
body_part = request.form.get('body-part')
layer = request.form.get('layer')
image = request.files.get('image')
prompt = f"""As an AI medical assistant, analyze the following information about a patient:
Gender: {gender}
Symptoms: {symptoms}
Affected Body Part: {body_part}
Layer Affected: {layer}
Based on this information, provide a detailed analysis considering the following:
1. Possible conditions: List and briefly describe potential conditions that match the symptoms and affected area.
2. Risk factors: Discuss any risk factors associated with the gender or affected body part.
3. Recommended next steps: Suggest appropriate medical tests or examinations that could help diagnose the condition.
4. General advice: Offer some general health advice related to the symptoms or affected area.
Important: This is not a diagnosis. Advise the patient to consult with a healthcare professional for an accurate diagnosis and treatment plan.
Format the response using the following structure:
<section>
<h2>Section Title</h2>
<p>Paragraph text</p>
<ul>
<li>List item 1</li>
<li>List item 2</li>
</ul>
</section>
Use <strong> for emphasis on important points.
"""
if image:
img = Image.open(BytesIO(image.read()))
img_byte_arr = BytesIO()
img.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()
image_base64 = base64.b64encode(img_byte_arr).decode('utf-8')
prompt += f"""
<section>
<h2>Image Analysis</h2>
<p>Analyze the provided image in relation to the patient's symptoms and affected body part. Consider:</p>
<ul>
<li>Any visible symptoms or abnormalities</li>
<li>Correlation between the image and the reported symptoms</li>
<li>Additional insights the image might provide about the patient's condition</li>
</ul>
</section>
Image data: data:image/png;base64,{image_base64}
"""
response = model_vision.generate_content([prompt, Image.open(BytesIO(base64.b64decode(image_base64)))], safety_settings=safety_settings)
else:
response = model_text.generate_content([prompt], safety_settings=safety_settings)
analysis_text = response.text if hasattr(response, 'text') else response.parts[0].text
# Wrap the entire response in a div for styling
formatted_analysis = f'<div class="analysis-content">{analysis_text}</div>'
return jsonify({'analysis': formatted_analysis})
except Exception as e:
logging.error(f"Error in /analyze route: {e}")
return jsonify({'error': "Internal Server Error"}), 500
return render_template('analyze.html')
# Flowchart Generation Routes
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
def extract_text_from_docx(file_path):
doc = Document(file_path)
full_text = []
for para in doc.paragraphs:
if para.text.strip(): # Only include non-empty paragraphs
full_text.append(para.text)
return '\n'.join(full_text)
def extract_text_from_pdf(file_path):
with open(file_path, 'rb') as f:
pdfReader = PyPDF2.PdfReader(f)
full_text = []
for page in pdfReader.pages:
text = page.extract_text()
if text.strip(): # Only include non-empty pages
full_text.append(text)
return '\n'.join(full_text)
def clean_and_validate_json(text):
"""Clean and validate JSON from the model's response."""
json_match = re.search(r'\{[\s\S]*\}', text)
if not json_match:
return None
json_str = json_match.group()
json_str = re.sub(r'```json\s*', '', json_str)
json_str = re.sub(r'```\s*$', '', json_str)
json_str = json_str.strip()
try:
json_data = json.loads(json_str)
if not all(key in json_data for key in ['nodes', 'edges']):
return None
for node in json_data['nodes']:
if not all(key in node for key in ['id', 'label']):
return None
node['shape'] = node.get('shape', 'box')
node['level'] = node.get('level', 0)
node['order'] = node.get('order', 1)
for edge in json_data['edges']:
if not all(key in edge for key in ['from', 'to']):
return None
edge['order'] = edge.get('order', 1)
return json_data
except json.JSONDecodeError:
return None
def generate_flowchart(topic, chart_type, animation, detail_level, document_text=None):
max_text_length = 4000
if document_text:
topic_prompt = f"Generate a hierarchical {'mind map' if chart_type == 'mind_map' else 'flowchart'} based on this content:\n\n{document_text}\n\n"
else:
topic_prompt = f"Generate a hierarchical {'mind map' if chart_type == 'mind_map' else 'flowchart'} for: \"{topic}\".\n\n"
prompt = topic_prompt + f"""
Please create a {'mind map' if chart_type == 'mind_map' else 'flowchart'} that is {'animated' if animation == 'animated' else 'static'} and {'simple' if detail_level == 'simple' else 'normal' if detail_level == 'normal' else 'detailed'}.
Output a JSON object with this exact structure:
{{
"nodes": [
{{"id": 1, "label": "Start", "shape": "ellipse", "level": 0, "order": 1}},
{{"id": 2, "label": "Process", "shape": "box", "level": 1, "order": 2}}
],
"edges": [
{{"from": 1, "to": 2, "order": 1}}
]
}}
Rules:
1. Use only these shapes: "ellipse", "box", "diamond", "hexagon", "circle"
2. Each node must have a unique integer id
3. Level 0 is root, increasing for each sub-level
4. Include order for animation sequence
5. Keep labels clear and concise
6. Maximum 20 nodes for simple, 35 for normal, 50 for detailed
7. Output ONLY the JSON, no other text"""
try:
response = model.generate_content(prompt)
flowchart_data = clean_and_validate_json(response.text)
if flowchart_data is None:
return {"error": "Invalid JSON structure", "raw_response": response.text}
return flowchart_data
except Exception as e:
return {"error": f"Error generating flowchart: {str(e)}"}
def modify_flowchart(current_data, prompt, chart_type):
"""Modifies the current flowchart based on a user prompt."""
current_data_str = json.dumps(current_data)
prompt_text = f"""Given the current {'mind map' if chart_type == 'mind_map' else 'flowchart'} data:\n\n{current_data_str}\n\nModify it according to the following prompt: \"{prompt}\".
The output should be a JSON object with the same structure as before, representing the updated {'mind map' if chart_type == 'mind_map' else 'flowchart'}. Ensure that the node and edge IDs remain unique and consistent where applicable.
Output ONLY the JSON, no other text."""
try:
response = model.generate_content(prompt_text)
modified_data = clean_and_validate_json(response.text)
if modified_data is None:
return {"error": "Invalid JSON structure from modification", "raw_response": response.text}
return modified_data
except Exception as e:
return {"error": f"Error modifying flowchart: {str(e)}"}
@app.route('/get_flowchart_data', methods=['POST'])
def get_flowchart_data():
global current_flowchart_data
try:
data = request.form
topic = data.get('topic', '').strip()
chart_type = data.get('type', 'flowchart')
animation = data.get('animation', 'static')
detail_level = data.get('detail_level', 'normal')
document_text = None
file = request.files.get('file')
if file and file.filename:
if not allowed_file(file.filename):
return jsonify({"error": "Unsupported file type."}), 400
filename = secure_filename(file.filename)
temp_fd, temp_path = tempfile.mkstemp()
try:
with os.fdopen(temp_fd, 'wb') as temp_file:
file.save(temp_file)
if filename.lower().endswith('.docx'):
document_text = extract_text_from_docx(temp_path)
elif filename.lower().endswith('.pdf'):
document_text = extract_text_from_pdf(temp_path)
if not topic and document_text:
topic = "Flowchart from Document"
finally:
if os.path.exists(temp_path):
os.remove(temp_path)
if not topic and not file:
return jsonify({"error": "Please provide a topic or upload a document."}), 400
flowchart_data = generate_flowchart(topic, chart_type, animation, detail_level, document_text)
if 'error' in flowchart_data:
return jsonify(flowchart_data), 500
current_flowchart_data = flowchart_data # Store the generated data
nodes = [{
"id": node["id"],
"label": node["label"],
"shape": node.get("shape", "box"),
"order": node.get("order", 1),
"level": node.get("level", 0)
} for node in flowchart_data.get('nodes', [])]
edges = [{
"from": edge["from"],
"to": edge["to"],
"id": f"{edge['from']}-{edge['to']}",
"order": edge.get("order", 1)
} for edge in flowchart_data.get('edges', [])]
nodes.sort(key=lambda x: x['order'])
edges.sort(key=lambda x: x['order'])
return jsonify({
"nodes": nodes,
"edges": edges,
"animation": animation,
"chart_type": chart_type
})
except Exception as e:
logging.error(f"Error in get_flowchart_data: {str(e)}")
return jsonify({"error": "An unexpected error occurred."}), 500
@app.route('/add_node', methods=['POST'])
def add_node():
global current_flowchart_data
data = request.get_json()
new_node = data.get('node')
if new_node:
# Simple way to generate a new unique ID (can be improved)
new_id = max([node['id'] for node in current_flowchart_data['nodes']] or [0]) + 1
new_node['id'] = new_id
current_flowchart_data['nodes'].append(new_node)
return jsonify({"status": "success", "node": new_node})
return jsonify({"status": "error", "message": "Invalid node data"}), 400
@app.route('/delete_node/<int:node_id>', methods=['DELETE'])
def delete_node(node_id):
global current_flowchart_data
current_flowchart_data['nodes'] = [node for node in current_flowchart_data['nodes'] if node['id'] != node_id]
current_flowchart_data['edges'] = [edge for edge in current_flowchart_data['edges']
if edge['from'] != node_id and edge['to'] != node_id]
return jsonify({"status": "success"})
@app.route('/edit_node/<int:node_id>', methods=['PUT'])
def edit_node(node_id):
global current_flowchart_data
data = request.get_json()
new_label = data.get('node').get('label')
for node in current_flowchart_data['nodes']:
if node['id'] == node_id:
node['label'] = new_label
return jsonify({"status": "success", "node": node})
return jsonify({"status": "error", "message": "Node not found"}), 404
@app.route('/add_edge', methods=['POST'])
def add_edge():
global current_flowchart_data
data = request.get_json()
new_edge = data.get('edge')
if new_edge:
current_flowchart_data['edges'].append(new_edge)
return jsonify({"status": "success", "edge": new_edge})
return jsonify({"status": "error", "message": "Invalid edge data"}), 400
@app.route('/delete_edge/<from_id>/<to_id>', methods=['DELETE'])
def delete_edge(from_id, to_id):
global current_flowchart_data
current_flowchart_data['edges'] = [
edge for edge in current_flowchart_data['edges']
if not (str(edge['from']) == from_id and str(edge['to']) == to_id)
]
return jsonify({"status": "success"})
@app.route('/modify_flowchart_prompt', methods=['POST'])
def modify_flowchart_prompt():
global current_flowchart_data, is_chart_modifying
data = request.get_json()
prompt = data.get('prompt')
chart_type = data.get('chart_type', 'flowchart')
if not prompt:
return jsonify({"status": "error", "message": "Prompt cannot be empty"}), 400
if is_chart_modifying:
return jsonify({"status": "error", "message": "Chart is currently being modified, please wait..."}), 400
is_chart_modifying = True # set flag
try:
modified_data = modify_flowchart(current_flowchart_data, prompt, chart_type)
if 'error' in modified_data:
return jsonify(modified_data), 500
current_flowchart_data = modified_data # Update the current data
# Prepare the data for vis-network
nodes = [{
"id": node["id"],
"label": node["label"],
"shape": node.get("shape", "box"),
"order": node.get("order", 1),
"level": node.get("level", 0)
} for node in modified_data.get('nodes', [])]
edges = [{
"from": edge["from"],
"to": edge["to"],
"id": f"{edge['from']}-{edge['to']}",
"order": edge.get("order", 1)
} for edge in modified_data.get('edges', [])]
return jsonify({
"status": "success",
"nodes": nodes,
"edges": edges
})
except Exception as e:
return jsonify({"error": f"Error modifying flowchart: {str(e)}"})
finally:
is_chart_modifying = False # clear flag
@app.route('/send-email', methods=['POST'])
def send_email():
data = request.json
name = data.get('name')
email = data.get('email')
message = data.get('message')
mail_data = {
'Messages': [
{
"From": {
"Email": "21131A05C6@gvpce.ac.in", # Replace with your email
"Name": "Kv Nexus"
},
"To": [
{
"Email": "21131A05C6@gvpce.ac.in", # Replace with your email
"Name": "Kv Nexus"
}
],
"Subject": f"New Contact Form Submission from {name}",
"TextPart": f"Name: {name}\nEmail: {email}\nMessage: {message}",
"HTMLPart": f"<h3>New Contact Form Submission</h3><p><strong>Name:</strong> {name}</p><p><strong>Email:</strong> {email}</p><p><strong>Message:</strong> {message}</p>"
}
]
}
result = mailjet.send.create(data=mail_data)
if result.status_code == 200:
return jsonify({"message": "Email sent successfully!"}), 200
else:
return jsonify({"message": "Failed to send email."}), 500
#docuement summarize
# Token bucket for rate limiting
# Rate limiting parameters
REQUEST_LIMIT = 15
TIME_WINDOW = 60
class TokenBucket:
def __init__(self, tokens, fill_rate):
self.capacity = tokens
self.tokens = tokens
self.fill_rate = fill_rate
self.last_check = time.time()
self.lock = threading.Lock()
def get_token(self):
with self.lock:
now = time.time()
time_passed = now - self.last_check
self.tokens = min(self.capacity, self.tokens + time_passed * self.fill_rate)
self.last_check = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
# Initialize the token bucket (15 tokens, refill 1 token every 4 seconds)
token_bucket = TokenBucket(REQUEST_LIMIT, 1 / (TIME_WINDOW / REQUEST_LIMIT))
def rate_limit_check():
while not token_bucket.get_token():