Skip to content

Commit c7a1793

Browse files
committed
front back con
1 parent 2b760de commit c7a1793

4 files changed

Lines changed: 141 additions & 38 deletions

File tree

backend/topic_processor.py

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
from flask import Flask, jsonify, request
2+
from flask_cors import CORS
3+
import psutil
4+
import socket
5+
import signal
6+
import sys
7+
import time
8+
9+
app = Flask(__name__)
10+
# Configure CORS to allow all origins and methods
11+
CORS(app, resources={
12+
r"/*": {
13+
"origins": "*",
14+
"methods": ["GET", "POST", "OPTIONS"],
15+
"allow_headers": ["Content-Type", "Authorization"]
16+
}
17+
})
18+
19+
@app.route('/process-topics', methods=['GET', 'POST'])
20+
def process_topics():
21+
try:
22+
if request.method == 'POST':
23+
data = request.get_json()
24+
search_term = data.get('searchTerm', '').lower()
25+
else: # GET request
26+
search_term = request.args.get('searchTerm', '').lower()
27+
28+
# Updated topic data to match frontend mock data
29+
all_topics = [
30+
{"name": "visual-programming", "count": 342},
31+
{"name": "graph-theory", "count": 289},
32+
{"name": "network-analysis", "count": 256},
33+
{"name": "scientific-computing", "count": 198},
34+
{"name": "python", "count": 187},
35+
{"name": "javascript", "count": 165},
36+
{"name": "d3", "count": 142},
37+
{"name": "typescript", "count": 128},
38+
{"name": "react", "count": 112},
39+
{"name": "machine-learning", "count": 98},
40+
{"name": "data-science", "count": 87},
41+
{"name": "visualization", "count": 76},
42+
{"name": "neo4j", "count": 65},
43+
{"name": "graphql", "count": 54},
44+
{"name": "sigma-js", "count": 43},
45+
]
46+
47+
filtered_topics = [
48+
topic for topic in all_topics
49+
if search_term in topic["name"].lower()
50+
]
51+
52+
return jsonify({
53+
"success": True,
54+
"data": filtered_topics,
55+
"total": len(filtered_topics)
56+
})
57+
58+
except Exception as e:
59+
return jsonify({
60+
"success": False,
61+
"error": str(e),
62+
"message": "An error occurred while processing the request"
63+
}), 500
64+
65+
@app.route('/')
66+
def home():
67+
return "Hello World!"
68+
69+
def signal_handler(sig, frame):
70+
print('\nShutting down the server...')
71+
sys.exit(0)
72+
73+
if __name__ == '__main__':
74+
signal.signal(signal.SIGINT, signal_handler)
75+
print("Starting Flask server...")
76+
port = 5002
77+
78+
print(f"Server running on: http://127.0.0.1:{port}/process-topics")
79+
app.run(host='127.0.0.1', port=port, debug=True)

src/views/HomeView.tsx

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,10 +118,10 @@ const HomeView: FC = () => {
118118

119119
<div className="tags d-flex flex-wrap justify-content-center mb-4" style={{ maxWidth: "600px", margin: "0 auto" }}>
120120
{[
121-
"visual programming",
122-
"machine learning",
123-
"logic programming",
124-
"large language models",
121+
"visual-programming",
122+
"machine-learning",
123+
"logic-programming",
124+
"large-language-models",
125125
].map((tag) => (
126126
<button
127127
key={tag}

src/views/TopicHistogram.tsx

Lines changed: 44 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,13 @@
11
import React, { FC, useEffect, useState, useRef } from "react";
22
import { useLocation, useNavigate } from "react-router";
3-
import { FaArrowLeft, FaPlus, FaTimes, FaFilter, FaMagic, FaEdit, FaCheck, FaExclamationCircle, FaThumbsUp } from "react-icons/fa";
3+
import { FaArrowLeft } from "react-icons/fa";
44
import { MultiRangeSlider } from "../components/MultiRangeSlider";
55
import * as d3 from "d3"; // Make sure to install @types/d3 and d3
66

77
// import { getErrorMessage } from "../lib/errors";
88
import { useNotifications } from "../lib/notifications";
9-
import { FrequencySelector } from "../components/FrequencySelector";
109
import { TopicRefiner } from "../components/TopicRefiner";
1110

12-
// Mock data - replace with actual API calls in your implementation
13-
const mockTopicData = [
14-
{ name: "data-visualization", count: 342 },
15-
{ name: "graph-theory", count: 289 },
16-
{ name: "network-analysis", count: 256 },
17-
{ name: "scientific-computing", count: 198 },
18-
{ name: "python", count: 187 },
19-
{ name: "javascript", count: 165 },
20-
{ name: "d3", count: 142 },
21-
{ name: "typescript", count: 128 },
22-
{ name: "react", count: 112 },
23-
{ name: "machine-learning", count: 98 },
24-
{ name: "data-science", count: 87 },
25-
{ name: "visualization", count: 76 },
26-
{ name: "neo4j", count: 65 },
27-
{ name: "graphql", count: 54 },
28-
{ name: "sigma-js", count: 43 },
29-
];
30-
3111
// Topic Histogram Component
3212
interface TopicHistogramProps {
3313
data: Array<{ name: string; count: number }>;
@@ -145,7 +125,6 @@ const TopicHistogram: FC = () => {
145125
// Get both search term and user topic from location state
146126
const searchTerm = (location.state as { searchTerm?: string } | undefined)?.searchTerm || "";
147127
const userTopic = (location.state as { userTopic?: string } | undefined)?.userTopic || "";
148-
console.log("userTopic", userTopic);
149128

150129
// Add state for storing the user topic
151130
const [originalTopic, setOriginalTopic] = useState(userTopic);
@@ -161,7 +140,7 @@ const TopicHistogram: FC = () => {
161140

162141
// State for frequency range
163142
const [frequencyRange, setFrequencyRange] = useState({ min: 0, max: 100 });
164-
const maxCount = Math.max(...extractedTopics.map(item => item.count), 1);
143+
const maxCount = Math.max(...extractedTopics.map(item => item.count || 0), 1);
165144

166145
// Update frequency range when maxCount changes
167146
useEffect(() => {
@@ -199,17 +178,50 @@ const TopicHistogram: FC = () => {
199178
}
200179
}, [searchTerm, userTopic, navigate, notify]);
201180

202-
// Effect to simulate topic extraction when search term changes
181+
// Effect to handle topic extraction when search term changes
203182
useEffect(() => {
204-
if (searchTerm) {
205-
setIsLoading(true);
206-
// Simulate API call to extract topics
207-
setTimeout(() => {
208-
setExtractedTopics(mockTopicData);
183+
// Add a check for extractedTopics length to prevent refetching
184+
if (!userTopic || extractedTopics.length > 0) return;
185+
186+
setIsLoading(true);
187+
188+
fetch('http://127.0.0.1:5002/process-topics', {
189+
method: 'POST',
190+
headers: {
191+
'Content-Type': 'application/json',
192+
},
193+
body: JSON.stringify({
194+
topic: userTopic,
195+
searchTerm: searchTerm
196+
})
197+
})
198+
.then(response => {
199+
if (!response.ok) {
200+
throw new Error(`HTTP error! status: ${response.status}`);
201+
}
202+
return response.json();
203+
})
204+
.then(data => {
205+
if (data.success && data.data.length === 0) {
206+
notify({
207+
message: "No topics found for this search. Try a different topic.",
208+
type: "warning"
209+
});
210+
}
211+
setExtractedTopics(data.data || []);
212+
})
213+
.catch(error => {
214+
console.error('Fetch error:', error);
215+
notify({
216+
message: "Failed to fetch topics. Please try again.",
217+
type: "error"
218+
});
219+
setExtractedTopics([]);
220+
})
221+
.finally(() => {
209222
setIsLoading(false);
210-
}, 1000);
211-
}
212-
}, [searchTerm]);
223+
});
224+
}, [userTopic]);
213225

214226
// Effect to update selected topics based on frequency range
215227
useEffect(() => {
@@ -266,8 +278,6 @@ const TopicHistogram: FC = () => {
266278

267279
// Function to handle form submission for the final step
268280
const handleSubmit = () => {
269-
console.log("Final topics submitted:", finalTopics);
270-
// Navigate to graph view with the selected topics
271281
navigate('/graph', { state: { topics: finalTopics } });
272282
};
273283

start.sh

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/bin/bash
2+
3+
# Start the Flask backend server in the background
4+
echo "Starting backend server..."
5+
cd backend
6+
python topic_processor.py &
7+
8+
# Wait a moment for the backend to start
9+
sleep 2
10+
11+
# Start the frontend development server
12+
echo "Starting frontend server..."
13+
cd ..
14+
npm start

0 commit comments

Comments
 (0)