mr2along commited on
Commit
d558c26
·
verified ·
1 Parent(s): 96b96fe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -142
app.py CHANGED
@@ -1,142 +1,126 @@
1
- import requests
2
- from bs4 import BeautifulSoup
3
- from concurrent.futures import ThreadPoolExecutor, as_completed
4
- import re
5
- import pypub
6
- import os
7
- import time # Thư viện để tính thời gian
8
- import gradio as gr # Thêm thư viện Gradio
9
-
10
- # Hàm để phân tích URL và tạo api_url và base_url
11
- def parse_story_url(story_url):
12
- # Cố gắng tìm kiếm tên ID truyện từ URL
13
- match = re.search(r"https://truyenfull\.tv/([^/]+)(?:-f\d+)?\.(\d+)/", story_url)
14
- if match:
15
- story_name = match.group(1) # Trích xuất tên truyện
16
- story_id = match.group(3) # Trích xuất ID truyện
17
- api_url = f"https://truyenfull.tv/api/chapters/{story_id}/" # Tạo URL API
18
- base_url = f"https://truyenfull.tv/{story_name}/chuong-" # Tạo URL cơ bản cho các chương
19
- return story_name, story_id, api_url, base_url # Trả về thông tin đã trích xuất và tạo
20
- else:
21
- raise ValueError("URL không hợp lệ") # Ném lỗi nếu định dạng URL không hợp lệ
22
-
23
- # Hàm để lấy thông tin các chương từ API
24
- def get_chapter_info(api_url):
25
- response = requests.get(api_url)
26
- response.raise_for_status() # Ném lỗi nếu không thành công
27
- data = response.json()
28
- return data.get('items', [])
29
-
30
- # Hàm để lấy nội dung của một chương dựa trên thứ tự chương
31
- def get_chapter_content(chapter_index, base_url):
32
- chapter_url = base_url + str(chapter_index) + ".html"
33
- try:
34
- response = requests.get(chapter_url)
35
- response.raise_for_status()
36
- soup = BeautifulSoup(response.content, 'html.parser')
37
- content_div = soup.find('div', id='chapter-c', class_='chapter-c')
38
- return content_div.get_text(separator='\n').strip() if content_div else "Không tìm thấy nội dung chương."
39
- except Exception as e:
40
- print(f"Lỗi khi lấy nội dung chương {chapter_index}: {e}")
41
- return "Không thể lấy nội dung."
42
-
43
- # Hàm để lấy nội dung tất cả các chương và lưu vào file
44
- def get_all_chapters_content(story_url, start_chapter, max_chapters):
45
- story_name, story_id, api_url, base_url = parse_story_url(story_url)
46
-
47
- chapters = get_chapter_info(api_url)
48
- if not chapters:
49
- return "Không tìm thấy chương nào."
50
-
51
- # Giới hạn số chương tải xuống
52
- chapters_to_load = chapters[start_chapter - 1:start_chapter - 1 + max_chapters]
53
- chapter_contents = [] # Danh sách lưu nội dung các chương theo thứ tự
54
- total_time = 0 # Biến để tính tổng thời gian thực hiện từng chương
55
-
56
- # Sử dụng ThreadPoolExecutor để lấy nội dung các chương song song
57
- with ThreadPoolExecutor(max_workers=10) as executor:
58
- future_to_chapter = {executor.submit(get_chapter_content, idx + 1, base_url): idx + 1 for idx in range(len(chapters_to_load))}
59
- for future in as_completed(future_to_chapter):
60
- chapter_index = future_to_chapter[future]
61
- start_time = time.time() # Bắt đầu đo thời gian cho mỗi chương
62
- try:
63
- content = future.result()
64
- # Lưu nội dung chương vào danh sách theo thứ tự
65
- chapter_contents.append((chapter_index, content, chapters[chapter_index - 1]['chapter_name'])) # Thêm tiêu đề chương
66
- print(f"Đã lưu chương {chapter_index}")
67
- except Exception as e:
68
- print(f"Lỗi khi lấy nội dung chương {chapter_index}: {e}")
69
- end_time = time.time() # Kết thúc đo thời gian
70
- chapter_time = end_time - start_time
71
- total_time += chapter_time # Cộng dồn thời gian cho mỗi chương
72
- print(f"Thời gian tải chương {chapter_index}: {chapter_time:.2f} giây")
73
-
74
- # Tính tổng thời gian và thời gian trung bình cho mỗi chương
75
- avg_time_per_chapter = total_time / max_chapters if max_chapters > 0 else 0
76
- print(f"Tổng thời gian tải {max_chapters} chương: {total_time:.2f} giây")
77
- print(f"Thời gian trung bình cho mỗi chương: {avg_time_per_chapter:.2f} giây")
78
-
79
- # Ghi nội dung các chương vào file theo thứ tự đã lưu
80
- chapter_contents.sort(key=lambda x: x[0]) # Sắp xếp theo chỉ số chương
81
- output_file = f"{story_name}.txt"
82
- with open(output_file, 'w', encoding='utf-8') as f:
83
- for chapter_index, content, chapter_title in chapter_contents:
84
- chapter_name = f"{chapter_title}" # Tạo tên chương với tiêu đề
85
- f.write(f"{chapter_name}\n\n")
86
- f.write(f"{content}\n")
87
- f.write("-" * 50 + "\n")
88
-
89
- # Tạo file EPUB từ nội dung đã lưu
90
- epubfile=create_epub_from_chapters(chapter_contents, story_name)
91
-
92
- # Trả về kết quả
93
- return [f"Đã tải thành công {max_chapters} chương. Tổng thời gian: {total_time:.2f} giây, Thời gian trung bình: {avg_time_per_chapter:.2f} giây. File TXT: {output_file}",epubfile]
94
-
95
- # Hàm để tạo file EPUB từ nội dung các chương
96
- def create_epub_from_chapters(chapter_contents, story_name):
97
- try:
98
- # Tạo đối tượng Epub
99
- my_epub = pypub.Epub(story_name)
100
-
101
- # Thêm từng chương vào EPUB
102
- for chapter_index, content, chapter_title in chapter_contents:
103
- # Tạo chương từ nội dung đã có
104
- my_chapter = pypub.create_chapter_from_text(content, chapter_title)
105
- my_epub.add_chapter(my_chapter)
106
-
107
- # Lưu file EPUB
108
- output_directory = f"./{story_name}.epub"
109
- epubfile=my_epub.create(output_directory) # Lưu file EPUB
110
- print(f"Đã tạo file EPUB: {output_directory}")
111
-
112
- except Exception as e:
113
- print(f"Lỗi khi tạo file EPUB: {e}")
114
- return epubfile
115
- # Giao diện Gradio
116
- def gradio_interface(story_url, start_chapter, max_chapters):
117
- # Bắt đầu đo thời gian cho toàn bộ quá trình
118
- start_total_time = time.time()
119
-
120
- # Gọi hàm tải và xử lý nội dung
121
- result = get_all_chapters_content(story_url, int(start_chapter), int(max_chapters))
122
-
123
- # Kết thúc đo thời gian
124
- end_total_time = time.time()
125
-
126
- # Tính tổng thời gian cho toàn bộ quá trình
127
- total_process_time = end_total_time - start_total_time
128
- result += f"\nTổng thời gian hoàn thành tất cả các chức năng: {total_process_time:.2f} giây"
129
- return result
130
-
131
- # Tạo giao diện với Gradio
132
- gr.Interface(
133
- fn=gradio_interface,
134
- inputs=[
135
- gr.Textbox(label="URL Truyện", placeholder="Nhập URL của truyện từ truyenfull.tv"),
136
- gr.Textbox(label="Số chương bắt đầu", placeholder="Nhập số chương bắt đầu"),
137
- gr.Textbox(label="Số chương muốn tải", placeholder="Nhập số chương muốn tải")
138
- ],
139
- outputs=["text","file"],
140
- title="Truyện Full Downloader",
141
- description="Công cụ tải truyện từ truyenfull.tv và tạo file EPUB."
142
- ).launch()
 
1
+ import speech_recognition as sr
2
+ import difflib
3
+ import wave
4
+ import pyaudio
5
+ import gradio as gr
6
+
7
+ # Step 1: Record audio
8
+ def record_audio(filename):
9
+ chunk = 1024 # Record in chunks of 1024 samples
10
+ sample_format = pyaudio.paInt16 # 16 bits per sample
11
+ channels = 1
12
+ fs = 44100 # Record at 44100 samples per second
13
+ seconds = 10 # Length of recording
14
+
15
+ p = pyaudio.PyAudio() # Create an interface to PortAudio
16
+
17
+ print("Recording...")
18
+ stream = p.open(format=sample_format,
19
+ channels=channels,
20
+ rate=fs,
21
+ frames_per_buffer=chunk,
22
+ input=True)
23
+
24
+ frames = [] # Initialize array to store frames
25
+
26
+ # Store data in chunks for the specified duration
27
+ for _ in range(0, int(fs / chunk * seconds)):
28
+ data = stream.read(chunk)
29
+ frames.append(data)
30
+
31
+ # Stop and close the stream
32
+ stream.stop_stream()
33
+ stream.close()
34
+ p.terminate()
35
+
36
+ # Save the recorded audio as a WAV file
37
+ wf = wave.open(filename, 'wb')
38
+ wf.setnchannels(channels)
39
+ wf.setsampwidth(p.get_sample_size(sample_format))
40
+ wf.setframerate(fs)
41
+ wf.writeframes(b''.join(frames))
42
+ wf.close()
43
+
44
+ print("Recording completed.")
45
+
46
+ # Step 2: Transcribe the audio file
47
+ def transcribe_audio(filename):
48
+ recognizer = sr.Recognizer()
49
+
50
+ # Open the audio file for transcription
51
+ with sr.AudioFile(filename) as source:
52
+ audio = recognizer.record(source)
53
+ try:
54
+ # Recognize the audio using Google Web Speech API
55
+ print("Transcribing the audio...")
56
+ transcription = recognizer.recognize_google(audio)
57
+ print("Transcription completed.")
58
+ return transcription
59
+ except sr.UnknownValueError:
60
+ print("Google Speech Recognition could not understand the audio")
61
+ return ""
62
+ except sr.RequestError as e:
63
+ print(f"Error with Google Speech Recognition service: {e}")
64
+ return ""
65
+
66
+ # Step 3: Compare the transcribed text with the input paragraph
67
+ def compare_texts(reference_text, transcribed_text):
68
+ word_scores = []
69
+ reference_words = reference_text.split()
70
+ transcribed_words = transcribed_text.split()
71
+
72
+ sm = difflib.SequenceMatcher(None, reference_text, transcribed_text)
73
+ similarity_score = round(sm.ratio() * 100, 2)
74
+
75
+ for i, word in enumerate(reference_words):
76
+ try:
77
+ if word.lower() == transcribed_words[i].lower():
78
+ word_scores.append({"word": word, "quality_score": 100})
79
+ else:
80
+ word_scores.append({"word": word, "quality_score": 50}) # Assuming 50 if it's wrong
81
+ except IndexError:
82
+ word_scores.append({"word": word, "quality_score": 0})
83
+
84
+ fidelity_class = "CORRECT" if similarity_score > 50 else "INCORRECT"
85
+
86
+ output = {
87
+ "quota_remaining": -1,
88
+ "reference_text_from_application": reference_text,
89
+ "status": "success",
90
+ "text_score": {
91
+ "fidelity_class": fidelity_class,
92
+ "quality_score": similarity_score,
93
+ "text": reference_text,
94
+ "transcribedText": transcribed_text,
95
+ "word_score_list": word_scores
96
+ },
97
+ "version": "1.1"
98
+ }
99
+
100
+ return output
101
+
102
+ # Gradio Interface Function
103
+ def gradio_function(paragraph):
104
+ # Record the audio (the filename will be 'recorded_audio.wav')
105
+ record_audio("recorded_audio.wav")
106
+
107
+ # Transcribe the audio
108
+ transcribed_text = transcribe_audio("recorded_audio.wav")
109
+
110
+ # Compare the original paragraph with the transcribed text
111
+ comparison_result = compare_texts(paragraph, transcribed_text)
112
+
113
+ # Return comparison result
114
+ return comparison_result
115
+
116
+ # Gradio Interface
117
+ interface = gr.Interface(
118
+ fn=gradio_function,
119
+ inputs=gr.inputs.Textbox(lines=5, label="Input Paragraph"),
120
+ outputs="json",
121
+ title="Speech Recognition Comparison",
122
+ description="Input a paragraph, record your audio, and compare the transcription to the original text."
123
+ )
124
+
125
+ # Launch Gradio app
126
+ interface.launch()