Spaces:
Runtime error
Runtime error
dwfefef
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -8,10 +8,10 @@ import re
|
|
8 |
from youtube_transcript_api import YouTubeTranscriptApi
|
9 |
|
10 |
app = Flask(__name__)
|
11 |
-
CORS(app)
|
12 |
logging.basicConfig(level=logging.DEBUG)
|
13 |
|
14 |
-
# Initialize the client
|
15 |
CLIENT_URL = os.getenv("CLIENT_URL")
|
16 |
MODEL = os.getenv("MODEL")
|
17 |
|
@@ -21,7 +21,7 @@ if not MODEL:
|
|
21 |
raise ValueError("MODEL environment variable must be set")
|
22 |
|
23 |
app.logger.info(f"Initializing client with URL: {CLIENT_URL}")
|
24 |
-
client = Client(
|
25 |
|
26 |
# System message
|
27 |
system_message = """You are Echo 1.5, an AI assistant developed by Abhinav. Your purpose is to assist users with their queries and provide helpful information. You should always be polite, respectful, and informative in your responses.
|
@@ -31,7 +31,7 @@ Remember:
|
|
31 |
2. Be helpful and informative in your responses.
|
32 |
3. If relevant, you can mention IamWomen and their work for women's welfare.
|
33 |
4. Always maintain a respectful and professional tone.
|
34 |
-
5. If the user query requires you to search the internet, you should
|
35 |
Links:
|
36 |
Echo: echo.iamwomen.cloudns.be
|
37 |
Iamwomen: iamwomen.cloudns.be
|
@@ -39,42 +39,36 @@ Iamwomen_Instagram: https://www.instagram.com/i_am_woman.24"""
|
|
39 |
|
40 |
context = [{"role": "system", "content": system_message}]
|
41 |
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
match = re.search(pattern, url)
|
46 |
-
if match:
|
47 |
-
video_id = match.group().split('/')[-1].split('v=')[-1].split('&')[0]
|
48 |
-
return video_id
|
49 |
-
return None
|
50 |
|
51 |
def get_youtube_transcript(video_id):
|
52 |
try:
|
53 |
transcript = YouTubeTranscriptApi.get_transcript(video_id)
|
54 |
-
|
|
|
55 |
except Exception as e:
|
56 |
-
app.logger.error(f"Error fetching transcript: {str(e)}")
|
57 |
return None
|
58 |
|
59 |
-
def
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
user_request = re.sub(r'(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/\S+', '', user_input).strip()
|
64 |
-
return video_id, user_request, transcript
|
65 |
-
return None, user_input, None
|
66 |
|
67 |
def chat_with_ai(message, transcript=None):
|
68 |
app.logger.debug(f"Received message: {message}")
|
69 |
|
70 |
if transcript:
|
71 |
-
context.append({"role": "
|
72 |
|
73 |
context.append({"role": "user", "content": message})
|
74 |
|
|
|
75 |
full_prompt = "\n".join([f"{msg['role']}: {msg['content']}" for msg in context])
|
76 |
|
77 |
-
app.logger.debug(f"Making API call with prompt: {full_prompt[:100]}...")
|
78 |
try:
|
79 |
result = client.predict(
|
80 |
message=full_prompt,
|
@@ -85,12 +79,13 @@ def chat_with_ai(message, transcript=None):
|
|
85 |
param_6=0,
|
86 |
api_name="/chat"
|
87 |
)
|
88 |
-
app.logger.debug(f"Received result: {result[:100]}...")
|
89 |
except Exception as e:
|
90 |
app.logger.error(f"Error in API call: {str(e)}")
|
91 |
app.logger.error(traceback.format_exc())
|
92 |
raise
|
93 |
|
|
|
94 |
context.append({"role": "assistant", "content": result})
|
95 |
|
96 |
return result
|
@@ -108,11 +103,20 @@ def chat():
|
|
108 |
return jsonify({"error": "No user input provided"}), 400
|
109 |
|
110 |
app.logger.debug(f"Received request: {data}")
|
111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
try:
|
113 |
-
|
114 |
-
response
|
115 |
-
app.logger.debug(f"API response content: {response[:100]}...")
|
116 |
return jsonify({"response": response})
|
117 |
except Exception as e:
|
118 |
app.logger.error(f"Unexpected error: {str(e)}")
|
|
|
8 |
from youtube_transcript_api import YouTubeTranscriptApi
|
9 |
|
10 |
app = Flask(__name__)
|
11 |
+
CORS(app) # Enable CORS for all routes
|
12 |
logging.basicConfig(level=logging.DEBUG)
|
13 |
|
14 |
+
# Initialize the client (this loads the API)
|
15 |
CLIENT_URL = os.getenv("CLIENT_URL")
|
16 |
MODEL = os.getenv("MODEL")
|
17 |
|
|
|
21 |
raise ValueError("MODEL environment variable must be set")
|
22 |
|
23 |
app.logger.info(f"Initializing client with URL: {CLIENT_URL}")
|
24 |
+
client = Client(CLIENT_URL)
|
25 |
|
26 |
# System message
|
27 |
system_message = """You are Echo 1.5, an AI assistant developed by Abhinav. Your purpose is to assist users with their queries and provide helpful information. You should always be polite, respectful, and informative in your responses.
|
|
|
31 |
2. Be helpful and informative in your responses.
|
32 |
3. If relevant, you can mention IamWomen and their work for women's welfare.
|
33 |
4. Always maintain a respectful and professional tone.
|
34 |
+
5. If the user's query requires you to search the internet, you should said "I'm sorry, but the web search would be added soon."
|
35 |
Links:
|
36 |
Echo: echo.iamwomen.cloudns.be
|
37 |
Iamwomen: iamwomen.cloudns.be
|
|
|
39 |
|
40 |
context = [{"role": "system", "content": system_message}]
|
41 |
|
42 |
+
# Regex to detect YouTube URLs
|
43 |
+
youtube_url_pattern = re.compile(
|
44 |
+
r'(https?://)?(www\.)?(youtube|youtu|youtube-nocookie)\.(com|be)/.+')
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
def get_youtube_transcript(video_id):
|
47 |
try:
|
48 |
transcript = YouTubeTranscriptApi.get_transcript(video_id)
|
49 |
+
transcript_text = " ".join([item['text'] for item in transcript])
|
50 |
+
return transcript_text
|
51 |
except Exception as e:
|
52 |
+
app.logger.error(f"Error fetching YouTube transcript: {str(e)}")
|
53 |
return None
|
54 |
|
55 |
+
def extract_youtube_id(url):
|
56 |
+
# Extract video ID from URL
|
57 |
+
video_id_match = re.search(r"(?:v=|\/)([0-9A-Za-z_-]{11}).*", url)
|
58 |
+
return video_id_match.group(1) if video_id_match else None
|
|
|
|
|
|
|
59 |
|
60 |
def chat_with_ai(message, transcript=None):
|
61 |
app.logger.debug(f"Received message: {message}")
|
62 |
|
63 |
if transcript:
|
64 |
+
context.append({"role": "context", "content": transcript})
|
65 |
|
66 |
context.append({"role": "user", "content": message})
|
67 |
|
68 |
+
# Prepare the full prompt
|
69 |
full_prompt = "\n".join([f"{msg['role']}: {msg['content']}" for msg in context])
|
70 |
|
71 |
+
app.logger.debug(f"Making API call with prompt: {full_prompt[:100]}...") # Log first 100 chars of prompt
|
72 |
try:
|
73 |
result = client.predict(
|
74 |
message=full_prompt,
|
|
|
79 |
param_6=0,
|
80 |
api_name="/chat"
|
81 |
)
|
82 |
+
app.logger.debug(f"Received result: {result[:100]}...") # Log first 100 chars of result
|
83 |
except Exception as e:
|
84 |
app.logger.error(f"Error in API call: {str(e)}")
|
85 |
app.logger.error(traceback.format_exc())
|
86 |
raise
|
87 |
|
88 |
+
# Add AI response to context
|
89 |
context.append({"role": "assistant", "content": result})
|
90 |
|
91 |
return result
|
|
|
103 |
return jsonify({"error": "No user input provided"}), 400
|
104 |
|
105 |
app.logger.debug(f"Received request: {data}")
|
106 |
+
|
107 |
+
youtube_match = youtube_url_pattern.search(user_input)
|
108 |
+
transcript = None
|
109 |
+
|
110 |
+
if youtube_match:
|
111 |
+
youtube_url = youtube_match.group(0)
|
112 |
+
video_id = extract_youtube_id(youtube_url)
|
113 |
+
if video_id:
|
114 |
+
transcript = get_youtube_transcript(video_id)
|
115 |
+
user_input = youtube_url_pattern.sub('', user_input).strip()
|
116 |
+
|
117 |
try:
|
118 |
+
response = chat_with_ai(user_input, transcript)
|
119 |
+
app.logger.debug(f"API response content: {response[:100]}...") # Log first 100 chars of response
|
|
|
120 |
return jsonify({"response": response})
|
121 |
except Exception as e:
|
122 |
app.logger.error(f"Unexpected error: {str(e)}")
|