File size: 8,061 Bytes
d7a8925
 
 
 
c99885f
 
 
d7a8925
 
 
 
 
 
 
 
 
 
 
 
c99885f
 
d7a8925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c99885f
d7a8925
 
 
 
 
 
 
 
 
 
 
 
70c3b32
d7a8925
 
 
 
 
c99885f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7a8925
 
 
 
 
 
70c3b32
d7a8925
 
 
 
 
 
 
c99885f
d7a8925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c99885f
d7a8925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c99885f
 
 
 
d7a8925
 
 
c99885f
 
 
 
d7a8925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import React, { useState, useEffect, useRef } from 'react';
import { useParams } from 'react-router-dom';
import '../App.css';

// Use relative URLs in production, full URLs in development
const isDevelopment = window.location.hostname === 'localhost';
const API_URL = isDevelopment ? 'http://localhost:8000' : '';

interface Message {
  id: number;
  text: string;
  agent: string;
}

interface Podcast {
  id: number;
  title: string;
  description: string;
  audio_file: string;
  filename?: string;
  category?: string;
}

interface PodcastContext {
  topic: string;
  believer_chunks: string[];
  skeptic_chunks: string[];
}

const PodcastForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [podcast, setPodcast] = useState<Podcast | null>(null);
  const [podcastContext, setPodcastContext] = useState<PodcastContext | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputMessage, setInputMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string>("");
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  useEffect(() => {
    const fetchPodcastAndContext = async () => {
      try {
        if (!id) return;

        // Fetch podcast details
        const response = await fetch(`${API_URL}/api/audio-list`);
        if (!response.ok) {
          throw new Error('Failed to fetch podcasts');
        }
        const files = await response.json();
        
        const podcastList = files.map((file: any, index: number) => {
          const filename = file.filename;
          const parts = filename.split('-');
          let queryPart = '', descriptionPart = '', categoryWithExt = '';
          
          if (parts.length >= 3) {
            [queryPart, descriptionPart, categoryWithExt] = parts;
          } else {
            queryPart = parts[0] || '';
            descriptionPart = parts[1] || queryPart;
            categoryWithExt = parts[2] || 'general.mp3';
          }
          
          const category = categoryWithExt.replace('.mp3', '');
          
          return {
            id: index + 1,
            title: descriptionPart.replace(/_/g, ' ').replace(/^\w/, c => c.toUpperCase()),
            description: `A debate exploring ${queryPart.replace(/_/g, ' ')}`,
            audio_file: `${API_URL}${file.path}`,
            filename: filename,
            category: category.replace(/_/g, ' ')
          };
        });

        const selectedPodcast = podcastList.find(p => p.id === parseInt(id));
        if (selectedPodcast) {
          setPodcast(selectedPodcast);
          
          // Fetch podcast context
          const contextResponse = await fetch(`${API_URL}/api/podcast/${id}/context`);
          if (contextResponse.ok) {
            const contextData: PodcastContext = await contextResponse.json();
            setPodcastContext(contextData);
          }
        }
      } catch (err) {
        console.error('Error fetching podcast:', err);
        setError(err instanceof Error ? err.message : 'Failed to fetch podcast');
      }
    };

    fetchPodcastAndContext();
  }, [id]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!inputMessage.trim() || !id) return;

    const userMessage: Message = {
      id: messages.length + 1,
      text: inputMessage,
      agent: "user"
    };

    setMessages(prev => [...prev, userMessage]);
    setInputMessage('');
    setIsLoading(true);

    try {
      const response = await fetch(`${API_URL}/api/podcast-chat/${id}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          message: inputMessage
        })
      });

      if (!response.ok) {
        throw new Error(`Server error: ${response.status}`);
      }

      const data = await response.json();
      
      const botMessage: Message = {
        id: messages.length + 2,
        text: data.response,
        agent: "assistant"
      };

      setMessages(prev => [...prev, botMessage]);
    } catch (error) {
      console.error('Error sending message:', error);
      setMessages(prev => [...prev, {
        id: prev.length + 1,
        text: `Error: ${error instanceof Error ? error.message : 'Failed to send message'}`,
        agent: "system"
      }]);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="podcast-form-container">

      <div className="chat-column">

        <div className="podcast-chat-container">

          {error && (

            <div className="error-message">Error: {error}</div>

          )}

          

          {podcast && (

            <div className="podcast-player-header">

              <h2 className="podcast-title">{podcast.title}</h2>

              {podcast.category && (

                <div className="category-pill">{podcast.category}</div>

              )}

              <p className="description">{podcast.description}</p>

              {podcastContext && (

                <p className="podcast-topic">Topic: {podcastContext.topic}</p>

              )}

              <div className="audio-player">

                <audio 

                  controls

                  src={podcast.audio_file}

                >

                  Your browser does not support the audio element.

                </audio>

              </div>

            </div>

          )}

          

          <div className="podcast-chat-messages">

            {messages.map((message) => (

              <div key={message.id} className={`message ${message.agent}-message`}>

                <div className="message-content">

                  <div className="agent-icon">

                    {message.agent === "user" ? "πŸ‘€" : 

                     message.agent === "system" ? "πŸ€–" : 

                     message.agent === "assistant" ? "πŸ€–" : "πŸ’¬"}

                  </div>

                  <div className="message-text-content">

                    <div className="agent-name">{message.agent}</div>

                    <div className="message-text">{message.text}</div>

                  </div>

                </div>

              </div>

            ))}

            {isLoading && (

              <div className="message system-message">

                <div className="message-content">

                  <div className="loading-dots">Processing</div>

                </div>

              </div>

            )}

            <div ref={messagesEndRef} />

          </div>



          <form onSubmit={handleSubmit} className="podcast-chat-input-form">

            <input

              type="text"

              value={inputMessage}

              onChange={(e) => setInputMessage(e.target.value)}

              placeholder="Ask a question about this podcast..."

              className="podcast-chat-input"

              disabled={isLoading}

            />

            <button type="submit" className="podcast-chat-send-button" disabled={isLoading}>

              Send

            </button>

          </form>

          

          {podcastContext && (

            <div className="relevant-chunks">

              <div className="chunk-section">

                <h4>Key Points</h4>

                <ul>

                  {podcastContext.believer_chunks.map((chunk, i) => (

                    <li key={`believer-${i}`}>{chunk}</li>

                  ))}

                  {podcastContext.skeptic_chunks.map((chunk, i) => (

                    <li key={`skeptic-${i}`}>{chunk}</li>

                  ))}

                </ul>

              </div>

            </div>

          )}

        </div>

      </div>

    </div>
  );
};

export default PodcastForm;