Skip to content

Commit 943d8d5

Browse files
committed
fix ai explain
1 parent 64c9e12 commit 943d8d5

3 files changed

Lines changed: 69 additions & 18 deletions

File tree

backend/app/main.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,13 +101,19 @@ def extract_topic_name(s):
101101
def explain_topic():
102102
try:
103103
data = request.get_json()
104+
print("Received explain-topic request with data:", {k: v for k, v in data.items() if k != 'apiKey'}) # Log data without API key
104105

105106
topic = data.get("topic", "")
106107
search_term = data.get("searchTerm", "")
107108
original_topic = data.get("originalTopic", "")
108109
api_key = data.get("apiKey", "")
109110

110111
if not topic or not search_term or not original_topic:
112+
print("Missing required parameters:", {
113+
"topic": bool(topic),
114+
"search_term": bool(search_term),
115+
"original_topic": bool(original_topic)
116+
})
111117
return jsonify(
112118
{
113119
"success": False,
@@ -116,6 +122,7 @@ def explain_topic():
116122
), 400
117123

118124
if not api_key:
125+
print("Missing API key")
119126
return jsonify(
120127
{
121128
"success": False,
@@ -127,34 +134,46 @@ def explain_topic():
127134
prompt = f"""Explain '{topic}' in the context of '{search_term}'.
128135
If it's an abbreviation, what it stands for in '{search_term}'
129136
Keep it concise but informative (1-2 sentences)."""
137+
print("Generated prompt:", prompt)
130138

131139
try:
132140
# Create an event loop and run the async function
133141
loop = asyncio.new_event_loop()
134142
asyncio.set_event_loop(loop)
135143

144+
print("Initializing AI processor with Gemini model")
136145
# Use Gemini for explanations
137146
explanation = loop.run_until_complete(
138147
ai_processor.process_topics(
139148
model="gemini-1.5-flash",
140149
api_key=api_key, # Use the API key from the request
141150
prompt=prompt,
142151
topics=[topic],
152+
search_term=search_term # Add the missing search_term parameter
143153
)
144154
)
145155
loop.close()
146156

157+
print("Received explanation:", explanation)
147158
if explanation and len(explanation) > 0:
148159
return jsonify({"success": True, "explanation": explanation[0]})
149160
else:
161+
print("No explanation generated")
150162
return jsonify(
151163
{"success": False, "message": "Failed to generate explanation"}
152164
), 500
153165

154166
except Exception as ai_error:
155-
raise ai_error
167+
print("AI processing error:", str(ai_error))
168+
# Return a more detailed error response
169+
return jsonify({
170+
"success": False,
171+
"error": str(ai_error),
172+
"message": "Error during AI processing"
173+
}), 500
156174

157175
except Exception as e:
176+
print("Top-level error in explain-topic:", str(e))
158177
return jsonify(
159178
{
160179
"success": False,

src/components/MultiRangeSlider.tsx

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,31 @@ interface MultiRangeSliderProps {
55
min: number;
66
max: number;
77
onChange: (values: { min: number; max: number }) => void;
8-
value: { min: number; max: number };
8+
value?: { min: number; max: number };
99
}
1010

1111
export const MultiRangeSlider: React.FC<MultiRangeSliderProps> = ({
1212
min,
1313
max,
1414
onChange,
15-
value
15+
value = { min: 0, max: 1 }
1616
}) => {
1717
const [minVal, setMinVal] = useState(value.min);
1818
const [maxVal, setMaxVal] = useState(value.max);
1919
const minValRef = useRef(value.min);
2020
const maxValRef = useRef(value.max);
2121
const range = useRef<HTMLDivElement>(null);
22+
const isUpdatingRef = useRef(false);
23+
24+
// Update internal state when value prop changes
25+
useEffect(() => {
26+
if (!isUpdatingRef.current) {
27+
setMinVal(value.min);
28+
setMaxVal(value.max);
29+
minValRef.current = value.min;
30+
maxValRef.current = value.max;
31+
}
32+
}, [value.min, value.max]);
2233

2334
// Convert to percentage
2435
const getPercent = useCallback(
@@ -49,21 +60,34 @@ export const MultiRangeSlider: React.FC<MultiRangeSliderProps> = ({
4960

5061
// Get min and max values when their state changes
5162
useEffect(() => {
52-
onChange({ min: minVal, max: maxVal });
63+
if (isUpdatingRef.current) {
64+
isUpdatingRef.current = false;
65+
onChange({ min: minVal, max: maxVal });
66+
}
5367
}, [minVal, maxVal, onChange]);
5468

69+
const handleMinChange = (event: React.ChangeEvent<HTMLInputElement>) => {
70+
const value = Math.min(Number(event.target.value), maxVal - 1);
71+
isUpdatingRef.current = true;
72+
setMinVal(value);
73+
minValRef.current = value;
74+
};
75+
76+
const handleMaxChange = (event: React.ChangeEvent<HTMLInputElement>) => {
77+
const value = Math.max(Number(event.target.value), minVal + 1);
78+
isUpdatingRef.current = true;
79+
setMaxVal(value);
80+
maxValRef.current = value;
81+
};
82+
5583
return (
5684
<div className="slider-container">
5785
<input
5886
type="range"
5987
min={min}
6088
max={max}
6189
value={minVal}
62-
onChange={(event) => {
63-
const value = Math.min(Number(event.target.value), maxVal - 1);
64-
setMinVal(value);
65-
minValRef.current = value;
66-
}}
90+
onChange={handleMinChange}
6791
className="thumb thumb--left"
6892
style={{ zIndex: minVal > max - 100 ? "5" : undefined }}
6993
/>
@@ -72,11 +96,7 @@ export const MultiRangeSlider: React.FC<MultiRangeSliderProps> = ({
7296
min={min}
7397
max={max}
7498
value={maxVal}
75-
onChange={(event) => {
76-
const value = Math.max(Number(event.target.value), minVal + 1);
77-
setMaxVal(value);
78-
maxValRef.current = value;
79-
}}
99+
onChange={handleMaxChange}
80100
className="thumb thumb--right"
81101
/>
82102

src/views/TopicHistogram.tsx

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -175,14 +175,16 @@ const TopicHistogram: FC = () => {
175175
const [selectedTopics, setSelectedTopics] = useState<string[]>([]);
176176

177177
// State for frequency range
178-
const [frequencyRange, setFrequencyRange] = useState({ min: 0, max: 100 });
178+
const [frequencyRange, setFrequencyRange] = useState({ min: 0, max: 1 });
179179
const [hasAdjustedRange, setHasAdjustedRange] = useState(false);
180180
const maxCount = Math.max(...extractedTopics.map(item => item.count || 0), 1);
181181

182-
// Update frequency range when maxCount changes
182+
// Update frequency range when maxCount changes, but only if it hasn't been adjusted yet
183183
useEffect(() => {
184-
setFrequencyRange({ min: 0, max: maxCount });
185-
}, [maxCount]);
184+
if (!hasAdjustedRange) {
185+
setFrequencyRange({ min: 0, max: 1 }); // Keep it at 0-1 until user adjusts
186+
}
187+
}, [maxCount, hasAdjustedRange]);
186188

187189
// State for final topics
188190
const [finalTopics, setFinalTopics] = useState<string[]>([]);
@@ -208,12 +210,17 @@ const TopicHistogram: FC = () => {
208210

209211
// Function to handle topic click
210212
const handleTopicClick = (topic: string) => {
213+
console.log('Topic clicked:', topic);
214+
console.log('Current API key:', apiKey ? 'Present' : 'Missing');
215+
211216
if (!apiKey) {
217+
console.log('No API key, showing modal');
212218
// Show API key modal if no key is set
213219
setShowApiKeyModal(true);
214220
return;
215221
}
216222

223+
console.log('Starting explanation fetch for topic:', topic);
217224
// Show explanation modal immediately with loading state
218225
setSelectedTopicForExplanation(topic);
219226
setTopicExplanation(""); // Clear previous explanation
@@ -334,7 +341,9 @@ const TopicHistogram: FC = () => {
334341

335342
// Function to fetch topic explanation
336343
const fetchTopicExplanation = async (topic: string) => {
344+
console.log('Fetching explanation for topic:', topic);
337345
if (!apiKey) {
346+
console.log('No API key in fetchTopicExplanation');
338347
notify({
339348
message: "Please set your Google API key first",
340349
type: "warning"
@@ -344,6 +353,7 @@ const TopicHistogram: FC = () => {
344353
}
345354

346355
try {
356+
console.log('Making API request to:', API_ENDPOINTS.EXPLAIN_TOPIC);
347357
const response = await fetch(API_ENDPOINTS.EXPLAIN_TOPIC, {
348358
method: 'POST',
349359
headers: {
@@ -357,11 +367,13 @@ const TopicHistogram: FC = () => {
357367
})
358368
});
359369

370+
console.log('Response status:', response.status);
360371
if (!response.ok) {
361372
throw new Error(`HTTP error! status: ${response.status}`);
362373
}
363374

364375
const data = await response.json();
376+
console.log('Response data:', data);
365377
if (data.success) {
366378
setTopicExplanation(data.explanation);
367379
} else {

0 commit comments

Comments
 (0)