Pijush2023 commited on
Commit
0b10da0
·
verified ·
1 Parent(s): 5d6f028

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -103
app.py CHANGED
@@ -891,65 +891,49 @@ from googlemaps import Client as GoogleMapsClient
891
  from diffusers import StableDiffusion3Pipeline
892
  import concurrent.futures
893
  from PIL import Image
894
- from flask import Flask, redirect, url_for, session
895
- from authlib.integrations.flask_client import OAuth
896
-
897
- # Initialize Flask app
898
- app = Flask(__name__)
899
- app.secret_key = os.urandom(24)
900
-
901
- # OAuth setup
902
- oauth = OAuth(app)
903
- google = oauth.register(
904
- name='google',
905
- client_id=os.environ['GOOGLE_CLIENT_ID'],
906
- client_secret=os.environ['GOOGLE_CLIENT_SECRET'],
907
- access_token_url='https://accounts.google.com/o/oauth2/token',
908
- authorize_url='https://accounts.google.com/o/oauth2/auth',
909
- authorize_params=None,
910
- access_token_params=None,
911
- refresh_token_url=None,
912
- redirect_uri='http://localhost:7860/oauth2callback',
913
- client_kwargs={'scope': 'openid profile email'},
914
- )
915
 
916
- @app.route('/')
917
- def home():
918
- email = dict(session).get('email', None)
919
- if email:
920
- return f'Hello, {email}!'
921
- return redirect('/login')
922
-
923
- @app.route('/login')
924
- def login():
925
- return google.authorize_redirect(url_for('authorize', _external=True))
926
-
927
- @app.route('/logout')
928
- def logout():
929
- session.pop('email', None)
930
- return redirect('/')
931
-
932
- @app.route('/authorize')
933
- def authorize():
934
- token = google.authorize_access_token()
935
- resp = google.get('https://www.googleapis.com/oauth2/v1/userinfo')
936
- user_info = resp.json()
937
- session['email'] = user_info['email']
938
- return redirect('/')
939
-
940
- @app.route('/oauth2callback')
941
- def oauth2callback():
942
- token = google.authorize_access_token()
943
- resp = google.get('https://www.googleapis.com/oauth2/v1/userinfo')
944
- user_info = resp.json()
945
- session['email'] = user_info['email']
946
- return redirect('/')
947
-
948
- # Your Gradio interface and other functions go here
949
-
950
- # Initialize logging
951
  logging.basicConfig(level=logging.DEBUG)
952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
953
  # Define function to get current time and date
954
  def get_current_time_and_date():
955
  now = datetime.now()
@@ -1170,32 +1154,6 @@ Keep the answer short and sweet and crisp. Always say "It was my pleasure!" at t
1170
  Question: {question}
1171
  Helpful Answer:"""
1172
 
1173
- # Initialize ChatOpenAI model
1174
- from langchain_openai import OpenAIEmbeddings, ChatOpenAI
1175
- from langchain_pinecone import PineconeVectorStore
1176
- from langchain.prompts import PromptTemplate
1177
- from langchain.chains import RetrievalQA
1178
- from langchain.chains.conversation.memory import ConversationBufferWindowMemory
1179
- from langchain.agents import Tool, initialize_agent
1180
-
1181
- embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
1182
-
1183
- # Initialize Pinecone
1184
- from pinecone import Pinecone
1185
- pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
1186
-
1187
- index_name = "omaha-details"
1188
- vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
1189
- retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
1190
-
1191
- chat_model = ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model='gpt-4o')
1192
-
1193
- conversational_memory = ConversationBufferWindowMemory(
1194
- memory_key='chat_history',
1195
- k=10,
1196
- return_messages=True
1197
- )
1198
-
1199
  QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
1200
  QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
1201
 
@@ -1297,25 +1255,7 @@ def generate_map(location_names):
1297
  ).add_to(m)
1298
  map_html = m._repr_html_()
1299
  return map_html
1300
- def transcribe_function(stream, new_chunk):
1301
- try:
1302
- sr, y = new_chunk[0], new_chunk[1]
1303
- except TypeError:
1304
- print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
1305
- return stream, "", None
1306
-
1307
- y = y.astype(np.float32) / np.max(np.abs(y))
1308
-
1309
- if stream is not None:
1310
- stream = np.concatenate([stream, y])
1311
- else:
1312
- stream = y
1313
 
1314
- result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
1315
-
1316
- full_text = result.get("text", "")
1317
-
1318
- return stream, full_text, result
1319
  def update_map_with_response(history):
1320
  if not history:
1321
  return ""
@@ -1385,6 +1325,10 @@ def update_images():
1385
  image_3 = generate_image(hardcoded_prompt_3)
1386
  return image_1, image_2, image_3
1387
 
 
 
 
 
1388
  with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
1389
  with gr.Row():
1390
  with gr.Column():
@@ -1416,13 +1360,11 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
1416
  refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3])
1417
 
1418
  login_button = gr.Button("Login with Google")
1419
- login_button.click(fn=lambda: redirect('/login'))
1420
 
1421
  demo.queue()
1422
  demo.launch(share=True)
1423
 
1424
- if __name__ == "__main__":
1425
- app.run(port=7860)
1426
 
1427
 
1428
 
 
891
  from diffusers import StableDiffusion3Pipeline
892
  import concurrent.futures
893
  from PIL import Image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
894
 
895
+ # Check if the token is already set in the environment variables
896
+ hf_token = os.getenv("HF_TOKEN")
897
+
898
+ if hf_token is None:
899
+ # If the token is not set, prompt for it (this should be done securely)
900
+ print("Please set your Hugging Face token in the environment variables.")
901
+ else:
902
+ # Login using the token
903
+ login(token=hf_token)
904
+
905
+ # Your application logic goes here
906
+ print("Logged in successfully to Hugging Face Hub!")
907
+
908
+ # Set up logging
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
909
  logging.basicConfig(level=logging.DEBUG)
910
 
911
+ # Initialize OpenAI embeddings
912
+ from langchain_openai import OpenAIEmbeddings, ChatOpenAI
913
+ from langchain_pinecone import PineconeVectorStore
914
+ from langchain.prompts import PromptTemplate
915
+ from langchain.chains import RetrievalQA
916
+ from langchain.chains.conversation.memory import ConversationBufferWindowMemory
917
+ from langchain.agents import Tool, initialize_agent
918
+
919
+ embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
920
+
921
+ # Initialize Pinecone
922
+ from pinecone import Pinecone
923
+ pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
924
+
925
+ index_name = "omaha-details"
926
+ vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
927
+ retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
928
+
929
+ chat_model = ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model='gpt-4o')
930
+
931
+ conversational_memory = ConversationBufferWindowMemory(
932
+ memory_key='chat_history',
933
+ k=10,
934
+ return_messages=True
935
+ )
936
+
937
  # Define function to get current time and date
938
  def get_current_time_and_date():
939
  now = datetime.now()
 
1154
  Question: {question}
1155
  Helpful Answer:"""
1156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1157
  QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
1158
  QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
1159
 
 
1255
  ).add_to(m)
1256
  map_html = m._repr_html_()
1257
  return map_html
 
 
 
 
 
 
 
 
 
 
 
 
 
1258
 
 
 
 
 
 
1259
  def update_map_with_response(history):
1260
  if not history:
1261
  return ""
 
1325
  image_3 = generate_image(hardcoded_prompt_3)
1326
  return image_1, image_2, image_3
1327
 
1328
+ def login_with_google():
1329
+ response = requests.get('http://localhost:5000/login')
1330
+ return response.url
1331
+
1332
  with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
1333
  with gr.Row():
1334
  with gr.Column():
 
1360
  refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3])
1361
 
1362
  login_button = gr.Button("Login with Google")
1363
+ login_button.click(fn=login_with_google)
1364
 
1365
  demo.queue()
1366
  demo.launch(share=True)
1367
 
 
 
1368
 
1369
 
1370