Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,35 +1,48 @@
|
|
| 1 |
-
|
| 2 |
-
import pandas as pd
|
| 3 |
import os
|
| 4 |
-
import
|
| 5 |
-
from
|
| 6 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
import pandas as pd
|
| 8 |
-
import
|
| 9 |
-
from
|
| 10 |
import requests
|
| 11 |
-
import
|
| 12 |
-
from
|
| 13 |
-
import
|
| 14 |
-
|
| 15 |
-
from pandasai import SmartDataframe, SmartDatalake
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
from wordcloud import WordCloud
|
| 20 |
-
import random
|
| 21 |
|
| 22 |
-
from dotenv import load_dotenv
|
| 23 |
-
import json
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
from dotenv import load_dotenv
|
| 27 |
|
| 28 |
-
load_dotenv()
|
| 29 |
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
app = Flask(__name__)
|
| 32 |
-
cors = CORS(app)
|
| 33 |
|
| 34 |
class FlaskResponse(ResponseParser):
|
| 35 |
def __init__(self, context) -> None:
|
|
@@ -55,62 +68,115 @@ class FlaskResponse(ResponseParser):
|
|
| 55 |
def format_other(self, result):
|
| 56 |
return str(result['value'])
|
| 57 |
|
| 58 |
-
gemini_api_key = os.environ['Gemini']
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
|
|
|
|
|
|
|
| 65 |
|
|
|
|
| 66 |
|
| 67 |
-
llm = GoogleGemini(api_key=gemini_api_key)
|
| 68 |
-
|
| 69 |
-
# Initialize Firebase app
|
| 70 |
-
if not firebase_admin._apps:
|
| 71 |
-
|
| 72 |
-
cred = credentials.Certificate("quant-app-99d09-firebase-adminsdk-6prb1-37f34e1c91.json")
|
| 73 |
-
firebase_admin.initialize_app(cred)
|
| 74 |
-
|
| 75 |
-
db = firestore.client()
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
@app.route("/predict", methods=["POST"])
|
| 81 |
-
@cross_origin()
|
| 82 |
-
def bot():
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
user_id = request.json.get("user_id")
|
| 86 |
-
user_question = request.json.get("user_question")
|
| 87 |
-
load_dotenv()
|
| 88 |
-
inventory_ref = db.collection("test_users").document(user_id).collection('inventory')
|
| 89 |
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
inventory_list = []
|
| 94 |
-
for doc in inventory_ref.stream():
|
| 95 |
-
a = doc.to_dict()
|
| 96 |
-
inventory_list.append(a)
|
| 97 |
-
|
| 98 |
-
sales_list = []
|
| 99 |
-
for doc in sales_ref.stream():
|
| 100 |
-
a = doc.to_dict()
|
| 101 |
-
sales_list.append(a)
|
| 102 |
-
|
| 103 |
-
inventory_df = pd.DataFrame(inventory_list)
|
| 104 |
-
sales_df = pd.DataFrame(sales_list)
|
| 105 |
-
|
| 106 |
-
lake = SmartDatalake([inventory_df, sales_df], config={"llm":llm, "response_parser":FlaskResponse, "enable_cache": False, "save_logs":False})
|
| 107 |
-
response = lake.chat(user_question)
|
| 108 |
-
print(user_question)
|
| 109 |
-
|
| 110 |
-
resp = str(response)
|
| 111 |
-
|
| 112 |
-
return jsonify(resp)
|
| 113 |
-
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask,request,make_response
|
|
|
|
| 2 |
import os
|
| 3 |
+
import logging
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
from heyoo import WhatsApp
|
| 6 |
+
import random
|
| 7 |
+
import shutil
|
| 8 |
+
from tempfile import NamedTemporaryFile
|
| 9 |
+
import assemblyai as aai
|
| 10 |
+
from pandasai.llm import GoogleGemini
|
| 11 |
+
from pandasai import SmartDataframe
|
| 12 |
+
from pandasai import Agent
|
| 13 |
+
from pandasai.responses.response_parser import ResponseParser
|
| 14 |
+
from langchain_experimental.agents import create_pandas_dataframe_agent
|
| 15 |
import pandas as pd
|
| 16 |
+
from langchain_google_genai import GoogleGenerativeAI
|
| 17 |
+
from langchain_google_genai.chat_models import ChatGoogleGenerativeAI
|
| 18 |
import requests
|
| 19 |
+
import base64
|
| 20 |
+
from pandasai.helpers import path
|
| 21 |
+
import uuid
|
| 22 |
+
import pandasai as pai
|
|
|
|
| 23 |
|
| 24 |
+
# load env data
|
| 25 |
+
load_dotenv()
|
|
|
|
|
|
|
| 26 |
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
'''
|
| 29 |
+
def modify_file_path(file_path):
|
| 30 |
+
guid = uuid.uuid4()
|
| 31 |
+
print(guid)
|
| 32 |
+
guid = str(uuid.uuid4())
|
| 33 |
+
new_filename = f"{guid}temp_chart.png"
|
| 34 |
+
new_file_path = os.path.join("/home/runner/Flasktestrairo/plots/", new_filename)
|
| 35 |
+
# Copy the file
|
| 36 |
+
shutil.copy2(file_path, new_file_path)
|
| 37 |
+
return new_file_path
|
| 38 |
+
'''
|
| 39 |
|
|
|
|
| 40 |
|
|
|
|
| 41 |
|
| 42 |
+
guid = uuid.uuid4()
|
| 43 |
+
new_filename = f"{guid}"
|
| 44 |
+
user_defined_path = os.path.join("/plots/", new_filename)
|
| 45 |
|
|
|
|
|
|
|
| 46 |
|
| 47 |
class FlaskResponse(ResponseParser):
|
| 48 |
def __init__(self, context) -> None:
|
|
|
|
| 68 |
def format_other(self, result):
|
| 69 |
return str(result['value'])
|
| 70 |
|
|
|
|
| 71 |
|
| 72 |
+
# messenger object
|
| 73 |
+
messenger = WhatsApp(
|
| 74 |
+
os.environ["whatsapp_token"],
|
| 75 |
+
phone_number_id=os.environ["phone_number_id"] )
|
| 76 |
|
| 77 |
+
aai.settings.api_key = os.environ["aai_key"]
|
| 78 |
+
transcriber = aai.Transcriber()
|
| 79 |
|
| 80 |
+
g_api_key = os.environ["google_api_key"]
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
|
| 84 |
+
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
VERIFY_TOKEN = "30cca545-3838-48b2-80a7-9e43b1ae8ce4"
|
| 87 |
+
|
| 88 |
+
#df = pd.read_excel("craig.xlsx")
|
| 89 |
+
df = pd.read_csv("small_business_data2.csv")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
llm = ChatGoogleGenerativeAI(model="gemini-pro", google_api_key=g_api_key, temperature=0.2)
|
| 93 |
+
|
| 94 |
+
def generateResponse(prompt):
|
| 95 |
+
llm = GoogleGemini(api_key=g_api_key)
|
| 96 |
+
pandas_agent = Agent(df,config={"llm":llm, "save_charts_path": user_defined_path,"save_charts": True,"response_parser":FlaskResponse, "enable_cache": False, "conversational":True})
|
| 97 |
+
answer = pandas_agent.chat(prompt)
|
| 98 |
+
return answer
|
| 99 |
+
|
| 100 |
+
img_ID = "344744a88ad1098"
|
| 101 |
+
img_secret="3c542a40c215327045d7155bddfd8b8bc84aebbf"
|
| 102 |
+
|
| 103 |
+
url = "https://api.imgur.com/3/image"
|
| 104 |
+
headers = {"Authorization": f"Client-ID {img_ID}"}
|
| 105 |
+
|
| 106 |
+
def respond(query_str:str):
|
| 107 |
+
response = "hello, I don't have a brain yet"
|
| 108 |
+
return response
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@app.route("/", methods=["GET", "POST"])
|
| 112 |
+
def hook():
|
| 113 |
+
if request.method == "GET":
|
| 114 |
+
if request.args.get("hub.verify_token") == VERIFY_TOKEN:
|
| 115 |
+
logging.info("Verified webhook")
|
| 116 |
+
response = make_response(request.args.get("hub.challenge"), 200)
|
| 117 |
+
response.mimetype = "text/plain"
|
| 118 |
+
return response
|
| 119 |
+
logging.error("Webhook Verification failed")
|
| 120 |
+
return "Invalid verification token"
|
| 121 |
+
|
| 122 |
+
# get message update..
|
| 123 |
+
data = request.get_json()
|
| 124 |
+
changed_field = messenger.changed_field(data)
|
| 125 |
+
|
| 126 |
+
if changed_field == "messages":
|
| 127 |
+
new_message = messenger.get_mobile(data)
|
| 128 |
+
if new_message:
|
| 129 |
+
mobile = messenger.get_mobile(data)
|
| 130 |
+
message_type = messenger.get_message_type(data)
|
| 131 |
+
|
| 132 |
+
if message_type == "text":
|
| 133 |
+
message = messenger.get_message(data)
|
| 134 |
+
# Handle greetings
|
| 135 |
+
if message.lower() in ("hi", "hello", "help", "how are you"):
|
| 136 |
+
response = "Hi there! My name is BuzyHelper. How can I help you today?"
|
| 137 |
+
messenger.send_message(message=f"{response}",recipient_id=mobile)
|
| 138 |
+
else:
|
| 139 |
+
response = str(generateResponse(message))
|
| 140 |
+
print("Response:", response)
|
| 141 |
+
logging.info(f"\nAnswer: {response}\n")
|
| 142 |
+
# Check if response is a string and represents a valid image path
|
| 143 |
+
if isinstance(response, str) and os.path.isfile(os.path.join(response)):
|
| 144 |
+
image_path = os.path.join(response)
|
| 145 |
+
print("My image path:", image_path)
|
| 146 |
+
with open(image_path, "rb") as file:
|
| 147 |
+
data = file.read()
|
| 148 |
+
base64_data = base64.b64encode(data)
|
| 149 |
+
|
| 150 |
+
# Upload image to Imgur and get URL
|
| 151 |
+
response = requests.post(url, headers=headers, data={"image": base64_data})
|
| 152 |
+
url1= response.json()["data"]["link"]
|
| 153 |
+
print(url1)
|
| 154 |
+
|
| 155 |
+
messenger.send_image(image=url1, recipient_id=mobile)
|
| 156 |
+
else:
|
| 157 |
+
# Handle cases where response is not a valid image path
|
| 158 |
+
messenger.send_message(message=f"{response}", recipient_id=mobile)
|
| 159 |
+
|
| 160 |
+
elif message_type == "audio":
|
| 161 |
+
audio = messenger.get_audio(data)
|
| 162 |
+
audio_id, mime_type = audio["id"], audio["mime_type"]
|
| 163 |
+
audio_url = messenger.query_media_url(audio_id)
|
| 164 |
+
audio_filename = messenger.download_media(audio_url, mime_type)
|
| 165 |
+
transcript =transcriber.transcribe(audio_filename)
|
| 166 |
+
print(audio_filename)
|
| 167 |
+
print(transcript.text)
|
| 168 |
+
res = transcript.text
|
| 169 |
+
logging.info(f"\nAudio: {audio}\n")
|
| 170 |
+
response = str(generateResponse(res))
|
| 171 |
+
if isinstance(response, str):
|
| 172 |
+
messenger.send_message(message=f"{response}", recipient_id=mobile)
|
| 173 |
+
elif isinstance(response, str) and os.path.isfile(response):
|
| 174 |
+
messenger.send_image(image_path=response, recipient_id=mobile)
|
| 175 |
+
|
| 176 |
+
else:
|
| 177 |
+
messenger.send_message(message="Please send me text or audio messages",recipient_id=mobile)
|
| 178 |
+
|
| 179 |
+
return "ok"
|
| 180 |
+
|
| 181 |
+
if __name__ == '__main__':
|
| 182 |
+
app.run(debug=True,host="0.0.0.0", port=7860)
|