File size: 13,036 Bytes
1165dfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import os
import requests
from requests.exceptions import RequestException
from bs4 import BeautifulSoup
import concurrent.futures
from io import BytesIO
import streamlit as st



def extract_part_numbers_and_manufacturers(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            links = soup.find_all('a')
            art_links = [link.get('href') for link in links if link.get('href') and link.get('href').startswith('/art')]

            if art_links:
                unique_art_links = list(set(art_links))
                parts_info = []
                part_urls = []
                for link in unique_art_links:
                    parts = link.split('-')
                    if len(parts) >= 4:
                        part_number = parts[1]
                        manufacturer = '-'.join(parts[2:-1])
                        part_link = f'https://alfacars.com.ua/index.php?route=product/search&search={part_number}'
                        part_info = f'{part_number} - {manufacturer}'
                        parts_info.append(part_info)
                        part_urls.append(part_link)

                if parts_info:
                    chunks = [parts_info[i:i + 100] for i in range(0, len(parts_info), 100)]
                    return chunks, part_urls
                else:
                    return None, None
            else:
                return None, None
        else:
            return None, None
    except requests.RequestException:
        return None, None


def get_manufacturer_info(manufacturer):
    try:
        url = f'https://avto.pro/makers/{manufacturer}'
        response = requests.get(url)
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            description = soup.find('div', {'class': 'maker-descr'}).text.strip()
            stars = soup.find('span', {'class': 'star-line'})
            stars_html = ''.join(['★' if star.get('class') and 'star-line__star--full' in star.get('class') else '☆' for star in stars.find_all('i')]) if stars else ''
            st.write(f'Информация о фирме {manufacturer}:\n{description}\n{stars_html}')
        else:
            st.write('Ошибка при получении информации о фирме.')
    except requests.RequestException:
        st.write('Информация о фирме не найдена. Попробуйте ввести VIN-код.')



def check_part_availability(part_urls):
    available_parts = []
    with concurrent.futures.ThreadPoolExecutor() as executor:
        futures = {executor.submit(check_part_url, url): url for url in part_urls}
        for future in concurrent.futures.as_completed(futures):
            url = futures[future]
            try:
                result = future.result()
                if result:
                    available_parts.append(url)
            except Exception as e:
                print(f"Ошибка при проверке {url}: {e}")
    return available_parts

def check_part_url(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            buy_button = soup.find('button', {'onclick': lambda x: x and 'cart.add' in x})
            if buy_button:
                return True
    except requests.RequestException as e:
        print(f"Ошибка при запросе {url}: {e}")
    return False

def get_clickable_links(part_numbers_and_manufacturers):
    clickable_links = ''
    for part_info in part_numbers_and_manufacturers:
        part_number, manufacturer = part_info.split(' - ')
        part_number = part_number.split(' ')[0]
        url = f'https://alfacars.com.ua/index.php?route=product/search&search={part_number}'
        try:
            response = requests.get(url)
            if response.status_code == 200:
                soup = BeautifulSoup(response.text, 'html.parser')
                buy_button = soup.find('button', {'onclick': lambda x: x and 'cart.add' in x})
                if buy_button:
                    clickable_links += f'<a href="{url}">{part_number}</a> - {manufacturer}\n'
                else:
                    clickable_links += f'{part_number} - {manufacturer}\n'
        except requests.RequestException:
            clickable_links += f'{part_number} - {manufacturer}\n'
    return clickable_links

def get_vin_info(vin_code):
    url = f"https://www.ilcats.ru/?vin={vin_code}&VinAction=Search"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'
    }
    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        soup = BeautifulSoup(response.content, "html.parser")
        table = soup.find("table")
        if table:
            rows = table.find_all("tr")
            info = ""
            for row in rows:
                cols = row.find_all("td")
                if len(cols) == 2:
                    label = cols[0].text.strip()
                    value = cols[1].text.strip()
                    info += f"{label}: {value}\n"
            st.text(info)
            st.write(f"Показать информацию: https://starchik-vinco.hf.space?vin_code={vin_code}")
        else:
            st.write("")
    else:
        st.write("Ошибка при запросе информации о VIN-коде. Попробуйте еще раз.")



def get_auto_lot_info(query):
    url = "https://ru.autoauctionspot.com/salvage-cars-auction/"
    payload = {
        'lot-type-available-to-bid': '1',
        'search-term': query,
    }
    images = []  # Определение переменной images перед использованием

    try:
        response = requests.post(url, data=payload)
        response.raise_for_status()

        soup = BeautifulSoup(response.content, 'html.parser')
        lot_title = soup.find('h1', class_='slider-name').text.strip()
        damage_info = soup.find('div', class_='char-line')
        damage_type_primary = damage_info.find('span', class_='char-info-envelope').text.strip()
        damage_type_secondary = damage_info.find_all('span', class_='char-info-envelope')[1].text.strip()

        lot_info = f"Лот: {lot_title}\nУщерб: {damage_type_primary}, {damage_type_secondary}\n"

        char_wrap = soup.find_all('div', class_='char-wrap')
        for char_box in char_wrap:
            char_lines = char_box.find_all('div', class_='char-line')
            for char_line in char_lines:
                char_name = char_line.find('span', class_='char-name').text.strip()
                char_info = char_line.find('span', class_='char-info').text.strip()
                lot_info += f"{char_name}: {char_info}\n"

        car_slider = soup.find('div', class_='car-slider')
        image_links = [figure.a['href'] for figure in car_slider.find_all('figure')]

        for link in image_links:
            image_response = requests.get(link)
            image_data = BytesIO(image_response.content)
            images.append(image_data)

        final_bid_info = soup.find('div', class_='copart-bid_final')
        final_bid_title = final_bid_info.find('span', class_='copart-bid-title').text.strip()
        final_bid_amount = final_bid_info.find('span', class_='copart-price').text.strip()
        final_bid_info = f"{final_bid_title}: {final_bid_amount}"

        return lot_info, images, final_bid_info

    except requests.RequestException as e:
        print(f"Ошибка при запросе {url}: {e}")
        return None, None, None
    except Exception as e:
        print(f"Необработанная ошибка в get_auto_lot_info: {e}")
        return None, None, None



def search_part_info(part_code):
    found_results = False

    try:
        query = part_code.replace(' ', '+')
        url = f'https://dok.ua/result2/query?q={query}'

        response = requests.get(url)
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            links = soup.find_all('a')
            found_link = None
            for link in links:
                href = link.get('href')
                if href and '/result2/art?id=' in href:
                    found_link = href
                    break

            if found_link:
                found_url = f'https://dok.ua{found_link}'
                part_info_chunks, _ = extract_part_numbers_and_manufacturers(found_url)
                if part_info_chunks:
                    part_numbers_and_manufacturers = [part_info for part_info_chunk in part_info_chunks for part_info in part_info_chunk]
                    part_info_text = '\n'.join(part_numbers_and_manufacturers) + '\n'

                    st.text(part_info_text)

                    clickable_links = get_clickable_links(part_numbers_and_manufacturers)
                    st.markdown(clickable_links, unsafe_allow_html=True)
                    found_results = True
                else:
                    get_manufacturer_info(part_code)
            else:
                lot_info, images, final_bid_info = get_auto_lot_info(query)

                if lot_info is not None and images is not None and final_bid_info is not None:
                    st.text((lot_info or '') + "\n" + (final_bid_info or ''))

                    if images:
                        st.image(images)
                    found_results = True
                    get_vin_info(part_code)
                else:
                    st.text("Нет результатов...")

        else:
            st.text(f"Ошибка при запросе {url}. Статус код: {response.status_code}")
            if not found_link and not found_results:
                st.text('Информация не найдена')

    except Exception as e:
        st.text(f"Ошибка в обработчике сообщений: {e}")
        if not found_results:
            st.text('Что-то пошло не так... Пожалуйста, попробуйте позже.')



if __name__ == '__main__':
    st.title("Alfabot Streamlit")

    part_code = st.text_input("Введите код запчасти, VIN-код или название фирмы")
    if st.button("Поиск информации"):
        st.text("Идет поиск информации...")
        
        found_results = False

        try:
            query = part_code.replace(' ', '+')
            url = f'https://dok.ua/result2/query?q={query}'

            response = requests.get(url)
            if response.status_code == 200:
                soup = BeautifulSoup(response.text, 'html.parser')
                links = soup.find_all('a')
                found_link = None
                for link in links:
                    href = link.get('href')
                    if href and '/result2/art?id=' in href:
                        found_link = href
                        break

                if found_link:
                    found_url = f'https://dok.ua{found_link}'
                    part_info_chunks, _ = extract_part_numbers_and_manufacturers(found_url)
                    if part_info_chunks:
                        part_numbers_and_manufacturers = [part_info for part_info_chunk in part_info_chunks for part_info in part_info_chunk]
                        part_info_text = '\n'.join(part_numbers_and_manufacturers) + '\n'

                        st.text(part_info_text)

                        clickable_links = get_clickable_links(part_numbers_and_manufacturers)
                        st.markdown(clickable_links, unsafe_allow_html=True)
                        found_results = True
                    else:
                        get_manufacturer_info(part_code)
                else:
                    lot_info, images, final_bid_info = get_auto_lot_info(query)

                    if lot_info is not None and images is not None and final_bid_info is not None:
                        st.text((lot_info or '') + "\n" + (final_bid_info or ''))

                        if images:
                            st.image(images)
                        found_results = True
                    else:
                        st.text("")

            else:
                st.text(f"Ошибка при запросе {url}. Статус код: {response.status_code}")
                if not found_link and not found_results:
                    st.text('Информация не найдена')

            get_vin_info(part_code)

        except Exception as e:
            st.text(f"Ошибка в обработчике сообщений: {e}")
            if not found_results:
                st.text('Что-то пошло не так... Пожалуйста, попробуйте позже.')