InterExblorer / app.py
afaqdean's picture
Upload 3 files
bf76cbc verified
# app.py
from flask import Flask, render_template, request
import subprocess
import json
import os
import sys
from sentence_transformers import SentenceTransformer
from pinecone import Pinecone
app = Flask(__name__)
PINECONE_API_KEY = os.environ.get('PINECONE_API_KEY')
PINECONE_SPACE_NAME = os.environ.get('PINECONE_SPACE_NAME')
model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
# Initialize Pinecone client
pc = Pinecone(api_key=PINECONE_API_KEY, environment='gcp-starter')
indexE = pc.Index(PINECONE_SPACE_NAME)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/search', methods=['POST'])
def search():
if request.method == 'POST':
query = request.form['query']
youtube_links = []
try:
# Encode the user-provided input
query_vector = model.encode(query)
# Convert the query vector to a list
query_vector_list = query_vector.tolist()
# Query Pinecone with the vector using the 'Index' object
results = indexE.query(
namespace='',
top_k=3,
include_values=True,
include_metadata=True,
vector=query_vector_list,
)
if results and 'matches' in results and results['matches']:
# Access metadata from each match
for match in results['matches']:
metadata = match.get('metadata', {})
video_id = metadata.get('video_id')
start_time = metadata.get('start_time')
time = int(start_time)
# Create a clickable YouTube link
youtube_link = f'https://www.youtube.com/watch?v={video_id}&t={time}s'
youtube_links.append(youtube_link)
except Exception as e:
# Handle exceptions gracefully
error_message = str(e)
output = {'error': error_message}
print(json.dumps(output))
else:
# No exceptions, render the template with results
if youtube_links:
return render_template('results.html', query=query, youtube_links=youtube_links)
else:
no_results_message = "No results found."
return render_template('results.html', query=query, no_results_message=no_results_message)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)