chenemii commited on
Commit
632b019
·
1 Parent(s): 4416c36
Files changed (2) hide show
  1. app/golf_swing_rag.py +143 -20
  2. app/streamlit_app.py +70 -2
app/golf_swing_rag.py CHANGED
@@ -1,16 +1,98 @@
1
- import pandas as pd
2
- import numpy as np
3
- import faiss
4
- from sentence_transformers import SentenceTransformer
5
- import streamlit as st
6
- import openai
7
- from dotenv import load_dotenv
8
- import os
9
- import json
10
- import pickle
11
- from typing import List, Dict, Tuple
12
- import re
13
- from datetime import datetime
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  # Load environment variables
16
  load_dotenv()
@@ -18,31 +100,72 @@ load_dotenv()
18
  class GolfSwingRAG:
19
  def __init__(self, csv_file_path: str = None):
20
  """Initialize the Golf Swing RAG system"""
 
 
 
 
 
21
  # Set default CSV path based on current working directory
22
  if csv_file_path is None:
23
- if os.path.exists("golf_swing_articles_complete.csv"):
24
- csv_file_path = "golf_swing_articles_complete.csv"
25
- elif os.path.exists("../golf_swing_articles_complete.csv"):
26
- csv_file_path = "../golf_swing_articles_complete.csv"
27
- else:
28
- raise FileNotFoundError("golf_swing_articles_complete.csv not found in current or parent directory")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
 
30
  self.csv_file_path = csv_file_path
 
 
31
  self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
 
 
32
  self.index = None
33
  self.chunks = []
34
  self.metadata = []
35
  self.openai_client = None
36
 
37
  # Initialize OpenAI client using Streamlit secrets
 
38
  try:
39
  openai_key = st.secrets.get("openai", {}).get("api_key", "")
40
  if openai_key:
41
  self.openai_client = openai.OpenAI(api_key=openai_key)
42
- except (KeyError, FileNotFoundError, AttributeError):
 
 
 
 
43
  # Fallback to environment variable if secrets not available
44
  if os.getenv("OPENAI_API_KEY"):
45
  self.openai_client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
 
 
 
 
 
 
46
 
47
  def load_and_process_data(self):
48
  """Load CSV data and process it for RAG"""
 
1
+ print("=== golf_swing_rag.py Import Debug ===")
2
+
3
+ try:
4
+ print("Importing pandas...")
5
+ import pandas as pd
6
+ print("✓ pandas imported successfully")
7
+ except ImportError as e:
8
+ print(f"✗ pandas import failed: {e}")
9
+
10
+ try:
11
+ print("Importing numpy...")
12
+ import numpy as np
13
+ print("✓ numpy imported successfully")
14
+ except ImportError as e:
15
+ print(f"✗ numpy import failed: {e}")
16
+
17
+ try:
18
+ print("Importing faiss...")
19
+ import faiss
20
+ print("✓ faiss imported successfully")
21
+ except ImportError as e:
22
+ print(f"✗ faiss import failed: {e}")
23
+
24
+ try:
25
+ print("Importing sentence_transformers...")
26
+ from sentence_transformers import SentenceTransformer
27
+ print("✓ sentence_transformers imported successfully")
28
+ except ImportError as e:
29
+ print(f"✗ sentence_transformers import failed: {e}")
30
+
31
+ try:
32
+ print("Importing streamlit...")
33
+ import streamlit as st
34
+ print("✓ streamlit imported successfully")
35
+ except ImportError as e:
36
+ print(f"✗ streamlit import failed: {e}")
37
+
38
+ try:
39
+ print("Importing openai...")
40
+ import openai
41
+ print("✓ openai imported successfully")
42
+ except ImportError as e:
43
+ print(f"✗ openai import failed: {e}")
44
+
45
+ try:
46
+ print("Importing dotenv...")
47
+ from dotenv import load_dotenv
48
+ print("✓ dotenv imported successfully")
49
+ except ImportError as e:
50
+ print(f"✗ dotenv import failed: {e}")
51
+
52
+ try:
53
+ print("Importing os...")
54
+ import os
55
+ print("✓ os imported successfully")
56
+ except ImportError as e:
57
+ print(f"✗ os import failed: {e}")
58
+
59
+ try:
60
+ print("Importing json...")
61
+ import json
62
+ print("✓ json imported successfully")
63
+ except ImportError as e:
64
+ print(f"✗ json import failed: {e}")
65
+
66
+ try:
67
+ print("Importing pickle...")
68
+ import pickle
69
+ print("✓ pickle imported successfully")
70
+ except ImportError as e:
71
+ print(f"✗ pickle import failed: {e}")
72
+
73
+ try:
74
+ print("Importing typing...")
75
+ from typing import List, Dict, Tuple
76
+ print("✓ typing imported successfully")
77
+ except ImportError as e:
78
+ print(f"✗ typing import failed: {e}")
79
+
80
+ try:
81
+ print("Importing re...")
82
+ import re
83
+ print("✓ re imported successfully")
84
+ except ImportError as e:
85
+ print(f"✗ re import failed: {e}")
86
+
87
+ try:
88
+ print("Importing datetime...")
89
+ from datetime import datetime
90
+ print("✓ datetime imported successfully")
91
+ except ImportError as e:
92
+ print(f"✗ datetime import failed: {e}")
93
+
94
+ print("=== End golf_swing_rag.py Import Debug ===")
95
+ print("")
96
 
97
  # Load environment variables
98
  load_dotenv()
 
100
  class GolfSwingRAG:
101
  def __init__(self, csv_file_path: str = None):
102
  """Initialize the Golf Swing RAG system"""
103
+ print("=== GolfSwingRAG Initialization Debug ===")
104
+ print(f"Current working directory: {os.getcwd()}")
105
+ print(f"__file__ location: {__file__}")
106
+ print(f"Directory of this file: {os.path.dirname(__file__)}")
107
+
108
  # Set default CSV path based on current working directory
109
  if csv_file_path is None:
110
+ # Try multiple possible locations
111
+ possible_paths = [
112
+ "golf_swing_articles_complete.csv", # Same directory
113
+ "../golf_swing_articles_complete.csv", # Parent directory
114
+ "../../golf_swing_articles_complete.csv", # Grandparent directory
115
+ "/app/golf_swing_articles_complete.csv", # Absolute path for Hugging Face
116
+ "/tmp/golf_swing_articles_complete.csv", # Alternative location
117
+ os.path.join(os.path.dirname(__file__), "..", "golf_swing_articles_complete.csv"), # Relative to script
118
+ ]
119
+
120
+ csv_file_path = None
121
+ for path in possible_paths:
122
+ print(f"Checking for CSV at: {path}")
123
+ if os.path.exists(path):
124
+ csv_file_path = path
125
+ print(f"✓ Found CSV at: {path}")
126
+ break
127
+ else:
128
+ print(f"✗ Not found at: {path}")
129
+
130
+ if csv_file_path is None:
131
+ print("✗ CSV file not found in any expected location!")
132
+ print(f"Files in current directory: {os.listdir('.')}")
133
+ if os.path.exists(".."):
134
+ print(f"Files in parent directory: {os.listdir('..')}")
135
+ raise FileNotFoundError("golf_swing_articles_complete.csv not found in any expected location")
136
 
137
+ print(f"Using CSV file: {csv_file_path}")
138
  self.csv_file_path = csv_file_path
139
+
140
+ print("Initializing SentenceTransformer...")
141
  self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
142
+ print("✓ SentenceTransformer initialized")
143
+
144
  self.index = None
145
  self.chunks = []
146
  self.metadata = []
147
  self.openai_client = None
148
 
149
  # Initialize OpenAI client using Streamlit secrets
150
+ print("Initializing OpenAI client...")
151
  try:
152
  openai_key = st.secrets.get("openai", {}).get("api_key", "")
153
  if openai_key:
154
  self.openai_client = openai.OpenAI(api_key=openai_key)
155
+ print("✓ OpenAI client initialized from Streamlit secrets")
156
+ else:
157
+ print("No OpenAI key found in Streamlit secrets")
158
+ except (KeyError, FileNotFoundError, AttributeError) as e:
159
+ print(f"Error accessing Streamlit secrets: {e}")
160
  # Fallback to environment variable if secrets not available
161
  if os.getenv("OPENAI_API_KEY"):
162
  self.openai_client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
163
+ print("✓ OpenAI client initialized from environment variable")
164
+ else:
165
+ print("No OpenAI API key found in environment variables either")
166
+
167
+ print("=== End GolfSwingRAG Initialization Debug ===")
168
+ print("")
169
 
170
  def load_and_process_data(self):
171
  """Load CSV data and process it for RAG"""
app/streamlit_app.py CHANGED
@@ -29,13 +29,65 @@ from utils.visualizer import create_annotated_video
29
  from utils.comparison import create_key_frame_comparison, extract_key_swing_frames
30
 
31
  # Import RAG functionality
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  try:
 
33
  from golf_swing_rag import GolfSwingRAG
 
34
  RAG_AVAILABLE = True
35
- except ImportError:
36
- RAG_AVAILABLE = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  st.warning("RAG functionality not available. Please ensure golf_swing_rag.py is in the app directory.")
38
 
 
 
 
39
  # Set page config
40
  st.set_page_config(page_title="Par-ity Project: Golf Swing Analysis 🏌️‍♀️",
41
  page_icon="🏌️‍♀️",
@@ -73,12 +125,28 @@ def load_rag_system():
73
  if not RAG_AVAILABLE:
74
  return None
75
  try:
 
76
  with st.spinner("Loading golf swing knowledge base..."):
 
77
  rag = GolfSwingRAG()
 
 
 
78
  rag.load_and_process_data()
 
 
 
79
  rag.create_embeddings()
 
 
 
 
80
  return rag
81
  except Exception as e:
 
 
 
 
82
  st.error(f"Error loading RAG system: {str(e)}")
83
  return None
84
 
 
29
  from utils.comparison import create_key_frame_comparison, extract_key_swing_frames
30
 
31
  # Import RAG functionality
32
+ print("=== RAG Import Debug Information ===")
33
+ print(f"Current working directory: {os.getcwd()}")
34
+ print(f"Python path: {sys.path}")
35
+ print(f"Files in current directory: {os.listdir('.')}")
36
+
37
+ # Check if we're in the app directory or project root
38
+ if os.path.exists("golf_swing_rag.py"):
39
+ print("✓ Found golf_swing_rag.py in current directory")
40
+ elif os.path.exists("app/golf_swing_rag.py"):
41
+ print("✓ Found golf_swing_rag.py in app/ subdirectory")
42
+ else:
43
+ print("✗ golf_swing_rag.py not found in current directory or app/ subdirectory")
44
+ print(f"Looking for: golf_swing_rag.py")
45
+ if os.path.exists("app"):
46
+ print(f"Files in app directory: {os.listdir('app')}")
47
+
48
  try:
49
+ print("Attempting to import golf_swing_rag...")
50
  from golf_swing_rag import GolfSwingRAG
51
+ print("✓ Successfully imported GolfSwingRAG from golf_swing_rag")
52
  RAG_AVAILABLE = True
53
+ except ImportError as e:
54
+ print(f"✗ ImportError: {e}")
55
+ print("Trying alternative import methods...")
56
+
57
+ # Try importing from app directory explicitly
58
+ try:
59
+ print("Trying: from app.golf_swing_rag import GolfSwingRAG")
60
+ from app.golf_swing_rag import GolfSwingRAG
61
+ print("✓ Successfully imported from app.golf_swing_rag")
62
+ RAG_AVAILABLE = True
63
+ except ImportError as e2:
64
+ print(f"✗ App import failed: {e2}")
65
+
66
+ # Try adding current directory to path and importing
67
+ try:
68
+ print("Adding current directory to sys.path and trying again...")
69
+ current_dir = os.path.dirname(os.path.abspath(__file__))
70
+ if current_dir not in sys.path:
71
+ sys.path.insert(0, current_dir)
72
+ print(f"Added to path: {current_dir}")
73
+
74
+ from golf_swing_rag import GolfSwingRAG
75
+ print("✓ Successfully imported after adding current dir to path")
76
+ RAG_AVAILABLE = True
77
+ except ImportError as e3:
78
+ print(f"✗ Final import attempt failed: {e3}")
79
+ RAG_AVAILABLE = False
80
+ st.error(f"RAG functionality not available. Import errors: {e}, {e2}, {e3}")
81
+
82
+ if RAG_AVAILABLE:
83
+ print("✓ RAG system is available!")
84
+ else:
85
+ print("✗ RAG system is NOT available")
86
  st.warning("RAG functionality not available. Please ensure golf_swing_rag.py is in the app directory.")
87
 
88
+ print("=== End RAG Import Debug ===")
89
+ print("")
90
+
91
  # Set page config
92
  st.set_page_config(page_title="Par-ity Project: Golf Swing Analysis 🏌️‍♀️",
93
  page_icon="🏌️‍♀️",
 
125
  if not RAG_AVAILABLE:
126
  return None
127
  try:
128
+ print("=== RAG System Loading Debug ===")
129
  with st.spinner("Loading golf swing knowledge base..."):
130
+ print("Creating GolfSwingRAG instance...")
131
  rag = GolfSwingRAG()
132
+ print("✓ GolfSwingRAG instance created successfully")
133
+
134
+ print("Loading and processing data...")
135
  rag.load_and_process_data()
136
+ print("✓ Data loaded and processed successfully")
137
+
138
+ print("Creating embeddings...")
139
  rag.create_embeddings()
140
+ print("✓ Embeddings created successfully")
141
+
142
+ print("✓ RAG system loaded successfully!")
143
+ print("=== End RAG System Loading Debug ===")
144
  return rag
145
  except Exception as e:
146
+ print(f"✗ Error loading RAG system: {str(e)}")
147
+ print(f"Error type: {type(e).__name__}")
148
+ import traceback
149
+ print(f"Full traceback: {traceback.format_exc()}")
150
  st.error(f"Error loading RAG system: {str(e)}")
151
  return None
152