File size: 6,948 Bytes
2b064f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import pathlib
import json
import hashlib
import random
import os

def load_content(file_path):
    if not file_path.exists():
        raise FileNotFoundError(f"Content file not found: {file_path}")
    with open(file_path, 'r') as file:
        content = [json.loads(line) for line in file if line.strip()]
    for item in content:
        item["id"] = hashlib.md5((item["question"] + item["answer"]).encode()).hexdigest()
        item["views"] = item.get("views", 0)
    return content

def select_next_question(content, seen_questions):
    unseen_questions = [item for item in content if item["id"] not in seen_questions]
    if unseen_questions:
        return random.choice(unseen_questions)
    else:
        min_views = min(item["views"] for item in content)
        least_viewed = [item for item in content if item["views"] == min_views]
        return random.choice(least_viewed)

class InterfaceCreator:
    def __init__(self, content, audio_dir):
        self.content = content
        self.seen_questions = set()
        self.audio_dir = audio_dir

    def get_audio_path(self, item_id, audio_type):
        return os.path.join(self.audio_dir, f"{item_id}_{audio_type}.mp3")

    def update_interface(self, current_item=None):
        if current_item is None or current_item.get('state') == 'answer':
            new_item = select_next_question(self.content, self.seen_questions)
            new_item['state'] = 'question'
            new_item['views'] += 1
            self.seen_questions.add(new_item["id"])
            question_audio = self.get_audio_path(new_item['id'], 'question')
            
            if not os.path.exists(question_audio):
                print(f"Warning: Audio file not found: {question_audio}")
                question_audio = None
            else:
                print(f"Audio file found: {question_audio}")
            
            return ("Show Answer ⏎", new_item['question'], "", question_audio, new_item)
        elif current_item.get('state') == 'question':
            current_item['state'] = 'answer'
            answer_audio = self.get_audio_path(current_item['id'], 'answer')
            
            if not os.path.exists(answer_audio):
                print(f"Warning: Audio file not found: {answer_audio}")
                answer_audio = None
            else:
                print(f"Audio file found: {answer_audio}")
            
            return ("Next Question ⏎", current_item['question'], current_item['answer'], answer_audio, current_item)

    def create_interface(self):
        custom_css = """
        .center-text { text-align: center; }
        #question-text, #answer-text { border: none; background: transparent; font-size: 20px; }
        #question-text textarea, #answer-text textarea { border: none; background: transparent; font-size: 20px; resize: none; overflow: hidden; min-height: 100px; max-height: 400px; }
        #audio-output { display: none !important; }
        #audio-output audio { display: none !important; }
        footer { display: none !important; }
        """

        shortcut_js = """
        <script>
        function autoResize(textarea) {
          textarea.style.height = 'auto';
          textarea.style.height = (textarea.scrollHeight) + 'px';
        }
        
        document.addEventListener('keydown', (e) => {
          if (e.key === "Enter" && e.target.tagName.toLowerCase() !== "textarea") {
            document.getElementById("primary-button").click();
          }
        });
        
        document.addEventListener('DOMContentLoaded', () => {
          const audioElement = document.querySelector('#audio-output audio');
          let audioQueue = [];
        
          function playNextAudio() {
            if (audioQueue.length > 0) {
              const nextAudio = audioQueue.shift();
              console.log("Attempting to play audio:", nextAudio);
              if (nextAudio) {
                audioElement.src = typeof nextAudio === 'string' ? nextAudio : URL.createObjectURL(new Blob([nextAudio], {type: 'audio/mpeg'}));
                audioElement.play().catch(e => console.error("Error playing audio:", e));
              } else {
                console.log("No audio to play");
              }
            }
          }
        
          audioElement.addEventListener('ended', playNextAudio);
        
          function setupGradioConfig() {
            if (window.gradio_config) {
              window.gradio_config.custom_interfaces = window.gradio_config.custom_interfaces || {};
              window.gradio_config.custom_interfaces["audio"] = (data) => { audioQueue = data; playNextAudio(); };
            }
          }
        
          setupGradioConfig();
          if (window.gradio_config) { window.gradio_config.artifialEventLoop = setupGradioConfig; }
        
          document.querySelectorAll('#question-text textarea, #answer-text textarea').forEach(textarea => {
            textarea.addEventListener('input', () => autoResize(textarea));
            autoResize(textarea);
          });
        
          // Use MutationObserver for dynamically added textareas
          new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
              if (mutation.type === 'childList') {
                mutation.addedNodes.forEach((node) => {
                  if (node.nodeType === Node.ELEMENT_NODE && node.tagName === 'TEXTAREA') {
                    autoResize(node);
                    node.addEventListener('input', () => autoResize(node));
                  }
                });
              }
            });
          }).observe(document.body, { childList: true, subtree: true });
        });
        </script>
        """
        with gr.Blocks(css=custom_css, head=shortcut_js) as demo:
            current_item = gr.State(None)
            primary_button = gr.Button("Show Answer ⏎", variant="primary", elem_id="primary-button")
            question_text = gr.Textbox(elem_id="question-text", show_label=False, label="Question", lines=5, max_lines=20, interactive=False)
            answer_text = gr.Textbox(elem_id="answer-text", show_label=False, label="Answer", lines=5, max_lines=20, interactive=False)
            audio_output = gr.Audio(elem_id="audio-output", visible=True, autoplay=True)
            primary_button.click(self.update_interface, inputs=[current_item], outputs=[primary_button, question_text, answer_text, audio_output, current_item])
            demo.load(self.update_interface, outputs=[primary_button, question_text, answer_text, audio_output, current_item])

        return demo

if __name__ == "__main__":
    BASE_DIR = pathlib.Path(os.getcwd())
    CONTENT_FILE = BASE_DIR / "content.jsonl"
    AUDIO_DIR = BASE_DIR / "audio"
    content = load_content(CONTENT_FILE)
    interface_creator = InterfaceCreator(content, AUDIO_DIR)
    demo = interface_creator.create_interface()
    demo.launch()