v1.3.7: Vollständige Version inkl. aller Funktionen, Modus 4: Nur Wikipedia-Suche
- Alle bisherigen Funktionen aus v1.3.6 bleiben erhalten - Neuer Modus 4 wurde implementiert, der ausschließlich Wikipedia-Suchen durchführt ohne ChatGPT-Anfragen - Modus 5 ermöglicht die LinkedIn-Kontaktsuche via SerpApi - Debug-Ausgaben wurden in allen Funktionen verbessert, sodass der Ablauf und die Ergebnisse besser nachvollzogen werden können - Der Startindex wird anhand des letzten Timestamps in Spalte AH korrekt ermittelt, sodass bestehende Datensätze nicht überschrieben werden
This commit is contained in:
@@ -14,7 +14,7 @@ import csv
|
|||||||
|
|
||||||
# ==================== KONFIGURATION ====================
|
# ==================== KONFIGURATION ====================
|
||||||
class Config:
|
class Config:
|
||||||
VERSION = "v1.3.7" # v1.3.7: Neuer Modus 4: Nur Wikipedia-Suche, keine ChatGPT-Anfragen.
|
VERSION = "v1.3.7" # v1.3.7: Alle bisherigen Funktionen beibehalten, neuer Modus 4: Nur Wikipedia-Suche.
|
||||||
LANG = "de"
|
LANG = "de"
|
||||||
CREDENTIALS_FILE = "service_account.json"
|
CREDENTIALS_FILE = "service_account.json"
|
||||||
SHEET_URL = "https://docs.google.com/spreadsheets/d/1u_gHr9JUfmV1-iviRzbSe3575QEp7KLhK5jFV_gJcgo"
|
SHEET_URL = "https://docs.google.com/spreadsheets/d/1u_gHr9JUfmV1-iviRzbSe3575QEp7KLhK5jFV_gJcgo"
|
||||||
@@ -134,189 +134,337 @@ def compare_umsatz_values(crm, wiki):
|
|||||||
diff_mio = abs(crm_val - wiki_val)
|
diff_mio = abs(crm_val - wiki_val)
|
||||||
return f"Abweichung: {int(round(diff_mio))} Mio €"
|
return f"Abweichung: {int(round(diff_mio))} Mio €"
|
||||||
|
|
||||||
# ==================== WIKIPEDIA SCRAPER ====================
|
def evaluate_umsatz_chatgpt(company_name, wiki_umsatz):
|
||||||
class WikipediaScraper:
|
try:
|
||||||
def __init__(self):
|
with open("api_key.txt", "r") as f:
|
||||||
wikipedia.set_lang(Config.LANG)
|
api_key = f.read().strip()
|
||||||
def _get_full_domain(self, website):
|
except Exception as e:
|
||||||
if not website:
|
debug_print(f"Fehler beim Lesen des API-Tokens: {e}")
|
||||||
return ""
|
return "k.A."
|
||||||
website = website.lower().strip()
|
openai.api_key = api_key
|
||||||
website = re.sub(r'^https?:\/\/', '', website)
|
prompt = (
|
||||||
website = re.sub(r'^www\.', '', website)
|
f"Bitte schätze den Umsatz in Mio. Euro für das Unternehmen '{company_name}'. "
|
||||||
return website.split('/')[0]
|
f"Die Wikipedia-Daten zeigen: '{wiki_umsatz}'. "
|
||||||
def _generate_search_terms(self, company_name, website):
|
"Antworte nur mit der Zahl."
|
||||||
terms = []
|
)
|
||||||
full_domain = self._get_full_domain(website)
|
try:
|
||||||
if full_domain:
|
response = openai.ChatCompletion.create(
|
||||||
terms.append(full_domain)
|
model="gpt-3.5-turbo",
|
||||||
normalized_name = normalize_company_name(company_name)
|
messages=[{"role": "user", "content": prompt}],
|
||||||
candidate = " ".join(normalized_name.split()[:2]).strip()
|
temperature=0.0
|
||||||
if candidate and candidate not in terms:
|
)
|
||||||
terms.append(candidate)
|
result = response.choices[0].message.content.strip()
|
||||||
if normalized_name and normalized_name not in terms:
|
debug_print(f"ChatGPT Umsatzschätzung: '{result}'")
|
||||||
terms.append(normalized_name)
|
|
||||||
debug_print(f"Generierte Suchbegriffe: {terms}")
|
|
||||||
return terms
|
|
||||||
def _validate_article(self, page, company_name, website):
|
|
||||||
full_domain = self._get_full_domain(website)
|
|
||||||
domain_found = False
|
|
||||||
if full_domain:
|
|
||||||
try:
|
|
||||||
html_raw = requests.get(page.url).text
|
|
||||||
soup = BeautifulSoup(html_raw, Config.HTML_PARSER)
|
|
||||||
infobox = soup.find('table', class_=lambda c: c and 'infobox' in c.lower())
|
|
||||||
if infobox:
|
|
||||||
links = infobox.find_all('a', href=True)
|
|
||||||
for link in links:
|
|
||||||
href = link.get('href').lower()
|
|
||||||
if href.startswith('/wiki/datei:'):
|
|
||||||
continue
|
|
||||||
if full_domain in href:
|
|
||||||
debug_print(f"Definitiver Link-Match in Infobox gefunden: {href}")
|
|
||||||
domain_found = True
|
|
||||||
break
|
|
||||||
if not domain_found and hasattr(page, 'externallinks'):
|
|
||||||
for ext_link in page.externallinks:
|
|
||||||
if full_domain in ext_link.lower():
|
|
||||||
debug_print(f"Definitiver Link-Match in externen Links gefunden: {ext_link}")
|
|
||||||
domain_found = True
|
|
||||||
break
|
|
||||||
except Exception as e:
|
|
||||||
debug_print(f"Fehler beim Extrahieren von Links: {str(e)}")
|
|
||||||
normalized_title = normalize_company_name(page.title)
|
|
||||||
normalized_company = normalize_company_name(company_name)
|
|
||||||
similarity = SequenceMatcher(None, normalized_title, normalized_company).ratio()
|
|
||||||
debug_print(f"Ähnlichkeit (normalisiert): {similarity:.2f} ({normalized_title} vs {normalized_company})")
|
|
||||||
threshold = 0.60 if domain_found else Config.SIMILARITY_THRESHOLD
|
|
||||||
return similarity >= threshold
|
|
||||||
def extract_first_paragraph(self, page_url):
|
|
||||||
try:
|
try:
|
||||||
response = requests.get(page_url)
|
value = float(result.replace(',', '.'))
|
||||||
soup = BeautifulSoup(response.text, Config.HTML_PARSER)
|
return str(int(round(value)))
|
||||||
paragraphs = soup.find_all('p')
|
except Exception as conv_e:
|
||||||
for p in paragraphs:
|
debug_print(f"Fehler bei der Verarbeitung der Umsatzschätzung '{result}': {conv_e}")
|
||||||
text = clean_text(p.get_text())
|
return result
|
||||||
if len(text) > 50:
|
except Exception as e:
|
||||||
return text
|
debug_print(f"Fehler beim Aufruf der ChatGPT API für Umsatzschätzung: {e}")
|
||||||
return "k.A."
|
|
||||||
except Exception as e:
|
|
||||||
debug_print(f"Fehler beim Extrahieren des ersten Absatzes: {e}")
|
|
||||||
return "k.A."
|
|
||||||
def extract_categories(self, soup):
|
|
||||||
cat_div = soup.find('div', id="mw-normal-catlinks")
|
|
||||||
if cat_div:
|
|
||||||
ul = cat_div.find('ul')
|
|
||||||
if ul:
|
|
||||||
cats = [clean_text(li.get_text()) for li in ul.find_all('li')]
|
|
||||||
return ", ".join(cats)
|
|
||||||
return "k.A."
|
return "k.A."
|
||||||
def _extract_infobox_value(self, soup, target):
|
|
||||||
infobox = soup.find('table', class_=lambda c: c and any(kw in c.lower() for kw in ['infobox', 'vcard', 'unternehmen']))
|
def validate_article_with_chatgpt(crm_data, wiki_data):
|
||||||
if not infobox:
|
crm_headers = "Firmenname;Website;Ort;Beschreibung;Aktuelle Branche;Beschreibung Branche extern;Anzahl Techniker;Umsatz (CRM);Anzahl Mitarbeiter (CRM)"
|
||||||
return "k.A."
|
wiki_headers = "Wikipedia URL;Wikipedia Absatz;Wikipedia Branche;Wikipedia Umsatz;Wikipedia Mitarbeiter;Wikipedia Kategorien"
|
||||||
keywords_map = {
|
prompt_text = (
|
||||||
'branche': ['branche', 'industrie', 'tätigkeit', 'geschäftsfeld', 'sektor', 'produkte', 'leistungen', 'aktivitäten', 'wirtschaftszweig'],
|
"Bitte überprüfe, ob die folgenden beiden Datensätze grundsätzlich zum gleichen Unternehmen gehören. "
|
||||||
'umsatz': ['umsatz', 'jahresumsatz', 'konzernumsatz', 'gesamtumsatz', 'erlöse', 'umsatzerlöse', 'einnahmen', 'ergebnis', 'jahresergebnis'],
|
"Berücksichtige dabei, dass leichte Abweichungen in Firmennamen (z. B. unterschiedliche Schreibweisen, Mutter-Tochter-Beziehungen) "
|
||||||
'mitarbeiter': ['mitarbeiter', 'beschäftigte', 'personal', 'mitarbeiterzahl', 'angestellte', 'belegschaft', 'personalstärke']
|
"oder im Ort (z. B. 'Oberndorf' vs. 'Oberndorf/Neckar') tolerierbar sind. "
|
||||||
}
|
"Vergleiche insbesondere den Firmennamen, den Ort und die Branche. Unterschiede im Umsatz können bis zu 10% abweichen. "
|
||||||
keywords = keywords_map.get(target, [])
|
"Wenn die Daten im Wesentlichen übereinstimmen, antworte ausschließlich mit 'OK'. "
|
||||||
for row in infobox.find_all('tr'):
|
"Falls nicht, nenne bitte den wichtigsten Grund und eine kurze Begründung, warum die Abweichung plausibel sein könnte.\n\n"
|
||||||
header = row.find('th')
|
f"CRM-Daten:\n{crm_headers}\n{crm_data}\n\n"
|
||||||
if header:
|
f"Wikipedia-Daten:\n{wiki_headers}\n{wiki_data}\n\n"
|
||||||
header_text = clean_text(header.get_text()).lower()
|
"Antwort: "
|
||||||
if any(kw in header_text for kw in keywords):
|
)
|
||||||
value = row.find('td')
|
try:
|
||||||
if value:
|
with open("api_key.txt", "r") as f:
|
||||||
raw_value = clean_text(value.get_text())
|
api_key = f.read().strip()
|
||||||
if target == 'branche':
|
except Exception as e:
|
||||||
clean_val = re.sub(r'\[.*?\]|\(.*?\)', '', raw_value)
|
debug_print(f"Fehler beim Lesen des API-Tokens: {e}")
|
||||||
return ' '.join(clean_val.split()).strip()
|
|
||||||
if target == 'umsatz':
|
|
||||||
return extract_numeric_value(raw_value, is_umsatz=True)
|
|
||||||
if target == 'mitarbeiter':
|
|
||||||
return extract_numeric_value(raw_value, is_umsatz=False)
|
|
||||||
return "k.A."
|
return "k.A."
|
||||||
def extract_full_infobox(self, soup):
|
openai.api_key = api_key
|
||||||
infobox = soup.find('table', class_=lambda c: c and any(kw in c.lower() for kw in ['infobox', 'vcard', 'unternehmen']))
|
try:
|
||||||
if not infobox:
|
response = openai.ChatCompletion.create(
|
||||||
return "k.A."
|
model="gpt-3.5-turbo",
|
||||||
return clean_text(infobox.get_text(separator=' | '))
|
messages=[{"role": "system", "content": prompt_text}],
|
||||||
def extract_fields_from_infobox_text(self, infobox_text, field_names):
|
temperature=0.0
|
||||||
result = {}
|
)
|
||||||
tokens = [token.strip() for token in infobox_text.split("|") if token.strip()]
|
result = response.choices[0].message.content.strip()
|
||||||
for i, token in enumerate(tokens):
|
debug_print(f"Validierungsantwort ChatGPT: '{result}'")
|
||||||
for field in field_names:
|
|
||||||
if field.lower() in token.lower():
|
|
||||||
j = i + 1
|
|
||||||
while j < len(tokens) and not tokens[j]:
|
|
||||||
j += 1
|
|
||||||
result[field] = tokens[j] if j < len(tokens) else "k.A."
|
|
||||||
return result
|
return result
|
||||||
def extract_company_data(self, page_url):
|
except Exception as e:
|
||||||
if not page_url:
|
debug_print(f"Fehler beim Validierungs-API-Aufruf: {e}")
|
||||||
return {
|
return "k.A."
|
||||||
'url': 'k.A.',
|
|
||||||
'first_paragraph': 'k.A.',
|
def evaluate_fsm_suitability(company_name, company_data):
|
||||||
'branche': 'k.A.',
|
try:
|
||||||
'umsatz': 'k.A.',
|
with open("api_key.txt", "r") as f:
|
||||||
'mitarbeiter': 'k.A.',
|
api_key = f.read().strip()
|
||||||
'categories': 'k.A.',
|
except Exception as e:
|
||||||
'full_infobox': 'k.A.'
|
debug_print(f"Fehler beim Lesen des API-Tokens (FSM): {e}")
|
||||||
}
|
return {"suitability": "k.A.", "justification": "k.A."}
|
||||||
|
openai.api_key = api_key
|
||||||
|
prompt = (
|
||||||
|
f"Bitte bewerte, ob das Unternehmen '{company_name}' für den Einsatz einer Field Service Management Lösung geeignet ist. "
|
||||||
|
"Berücksichtige, dass ein Unternehmen mit einem technischen Außendienst, idealerweise mit über 50 Technikern und "
|
||||||
|
"Disponenten, die mit der Planung mobiler Ressourcen beschäftigt sind, als geeignet gilt. Nutze dabei verifizierte "
|
||||||
|
"Wikipedia-Daten und deine eigene Einschätzung. Antworte ausschließlich mit 'Ja' oder 'Nein' und gib eine kurze Begründung."
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
response = openai.ChatCompletion.create(
|
||||||
|
model="gpt-3.5-turbo",
|
||||||
|
messages=[{"role": "system", "content": prompt}],
|
||||||
|
temperature=0.0
|
||||||
|
)
|
||||||
|
result = response.choices[0].message.content.strip()
|
||||||
|
debug_print(f"FSM-Eignungsantwort ChatGPT: '{result}'")
|
||||||
|
suitability = "k.A."
|
||||||
|
justification = ""
|
||||||
|
lines = result.split("\n")
|
||||||
|
if len(lines) == 1:
|
||||||
|
parts = result.split(" ", 1)
|
||||||
|
suitability = parts[0].strip()
|
||||||
|
justification = parts[1].strip() if len(parts) > 1 else ""
|
||||||
|
else:
|
||||||
|
for line in lines:
|
||||||
|
if line.lower().startswith("eignung:"):
|
||||||
|
suitability = line.split(":", 1)[1].strip()
|
||||||
|
elif line.lower().startswith("begründung:"):
|
||||||
|
justification = line.split(":", 1)[1].strip()
|
||||||
|
if suitability not in ["Ja", "Nein"]:
|
||||||
|
parts = result.split(" ", 1)
|
||||||
|
suitability = parts[0].strip()
|
||||||
|
justification = " ".join(result.split()[1:]).strip()
|
||||||
|
return {"suitability": suitability, "justification": justification}
|
||||||
|
except Exception as e:
|
||||||
|
debug_print(f"Fehler beim Aufruf der ChatGPT API für FSM-Eignungsprüfung: {e}")
|
||||||
|
return {"suitability": "k.A.", "justification": "k.A."}
|
||||||
|
|
||||||
|
def evaluate_servicetechnicians_estimate(company_name, company_data):
|
||||||
|
try:
|
||||||
|
with open("serpApiKey.txt", "r") as f:
|
||||||
|
serp_key = f.read().strip()
|
||||||
|
except Exception as e:
|
||||||
|
debug_print(f"Fehler beim Lesen des SerpAPI-Schlüssels (Servicetechniker): {e}")
|
||||||
|
return "k.A."
|
||||||
|
try:
|
||||||
|
with open("api_key.txt", "r") as f:
|
||||||
|
api_key = f.read().strip()
|
||||||
|
except Exception as e:
|
||||||
|
debug_print(f"Fehler beim Lesen des API-Tokens (Servicetechniker): {e}")
|
||||||
|
return "k.A."
|
||||||
|
openai.api_key = api_key
|
||||||
|
prompt = (
|
||||||
|
f"Bitte schätze auf Basis öffentlich zugänglicher Informationen (vor allem verifizierte Wikipedia-Daten) "
|
||||||
|
f"die Anzahl der Servicetechniker des Unternehmens '{company_name}' ein. "
|
||||||
|
"Gib die Antwort ausschließlich in einer der folgenden Kategorien aus: "
|
||||||
|
"'<50 Techniker', '>100 Techniker', '>200 Techniker', '>500 Techniker'."
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
response = openai.ChatCompletion.create(
|
||||||
|
model="gpt-3.5-turbo",
|
||||||
|
messages=[{"role": "system", "content": prompt}],
|
||||||
|
temperature=0.0
|
||||||
|
)
|
||||||
|
result = response.choices[0].message.content.strip()
|
||||||
|
debug_print(f"Schätzung Servicetechniker ChatGPT: '{result}'")
|
||||||
|
return result
|
||||||
|
except Exception as e:
|
||||||
|
debug_print(f"Fehler beim Aufruf der ChatGPT API für Servicetechniker-Schätzung: {e}")
|
||||||
|
return "k.A."
|
||||||
|
|
||||||
|
def evaluate_servicetechnicians_explanation(company_name, st_estimate, company_data):
|
||||||
|
try:
|
||||||
|
with open("api_key.txt", "r") as f:
|
||||||
|
api_key = f.read().strip()
|
||||||
|
except Exception as e:
|
||||||
|
debug_print(f"Fehler beim Lesen des API-Tokens (ST-Erklärung): {e}")
|
||||||
|
return "k.A."
|
||||||
|
openai.api_key = api_key
|
||||||
|
prompt = (
|
||||||
|
f"Bitte erkläre, warum du für das Unternehmen '{company_name}' die Anzahl der Servicetechniker als '{st_estimate}' geschätzt hast. "
|
||||||
|
"Berücksichtige dabei öffentlich zugängliche Informationen wie Branche, Umsatz, Mitarbeiterzahl und andere relevante Daten."
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
response = openai.ChatCompletion.create(
|
||||||
|
model="gpt-3.5-turbo",
|
||||||
|
messages=[{"role": "system", "content": prompt}],
|
||||||
|
temperature=0.0
|
||||||
|
)
|
||||||
|
result = response.choices[0].message.content.strip()
|
||||||
|
debug_print(f"Servicetechniker-Erklärung ChatGPT: '{result}'")
|
||||||
|
return result
|
||||||
|
except Exception as e:
|
||||||
|
debug_print(f"Fehler beim Aufruf der ChatGPT API für Servicetechniker-Erklärung: {e}")
|
||||||
|
return "k.A."
|
||||||
|
|
||||||
|
def map_internal_technicians(value):
|
||||||
|
try:
|
||||||
|
num = int(value)
|
||||||
|
except Exception:
|
||||||
|
return "k.A."
|
||||||
|
if num < 50:
|
||||||
|
return "<50 Techniker"
|
||||||
|
elif num < 100:
|
||||||
|
return ">100 Techniker"
|
||||||
|
elif num < 200:
|
||||||
|
return ">200 Techniker"
|
||||||
|
else:
|
||||||
|
return ">500 Techniker"
|
||||||
|
|
||||||
|
def wait_for_sheet_update(sheet, cell, expected_value, timeout=5):
|
||||||
|
start_time = time.time()
|
||||||
|
while time.time() - start_time < timeout:
|
||||||
try:
|
try:
|
||||||
response = requests.get(page_url)
|
current_value = sheet.acell(cell).value
|
||||||
soup = BeautifulSoup(response.text, Config.HTML_PARSER)
|
if current_value == expected_value:
|
||||||
full_infobox = self.extract_full_infobox(soup)
|
return True
|
||||||
extracted_fields = self.extract_fields_from_infobox_text(full_infobox, ['Branche', 'Umsatz', 'Mitarbeiter'])
|
|
||||||
raw_branche = extracted_fields.get('Branche', self._extract_infobox_value(soup, 'branche'))
|
|
||||||
raw_umsatz = extracted_fields.get('Umsatz', self._extract_infobox_value(soup, 'umsatz'))
|
|
||||||
raw_mitarbeiter = extracted_fields.get('Mitarbeiter', self._extract_infobox_value(soup, 'mitarbeiter'))
|
|
||||||
umsatz_val = extract_numeric_value(raw_umsatz, is_umsatz=True)
|
|
||||||
mitarbeiter_val = extract_numeric_value(raw_mitarbeiter, is_umsatz=False)
|
|
||||||
categories_val = self.extract_categories(soup)
|
|
||||||
first_paragraph = self.extract_first_paragraph(page_url)
|
|
||||||
return {
|
|
||||||
'url': page_url,
|
|
||||||
'first_paragraph': first_paragraph,
|
|
||||||
'branche': raw_branche,
|
|
||||||
'umsatz': umsatz_val,
|
|
||||||
'mitarbeiter': mitarbeiter_val,
|
|
||||||
'categories': categories_val,
|
|
||||||
'full_infobox': full_infobox
|
|
||||||
}
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
debug_print(f"Extraktionsfehler: {str(e)}")
|
debug_print(f"Fehler beim Lesen von Zelle {cell}: {e}")
|
||||||
return {
|
time.sleep(0.5)
|
||||||
'url': 'k.A.',
|
return False
|
||||||
'first_paragraph': 'k.A.',
|
|
||||||
'branche': 'k.A.',
|
# ==================== NEUE FUNKTION: LINKEDIN-KONTAKT-SUCHE MIT SERPAPI ====================
|
||||||
'umsatz': 'k.A.',
|
def search_linkedin_contact(company_name, website, position_query):
|
||||||
'mitarbeiter': 'k.A.',
|
try:
|
||||||
'categories': 'k.A.',
|
with open("serpApiKey.txt", "r") as f:
|
||||||
'full_infobox': 'k.A.'
|
serp_key = f.read().strip()
|
||||||
}
|
except Exception as e:
|
||||||
@retry_on_failure
|
debug_print("Fehler beim Lesen des SerpAPI-Schlüssels: " + str(e))
|
||||||
def search_company_article(self, company_name, website):
|
return None
|
||||||
search_terms = self._generate_search_terms(company_name, website)
|
query = f'site:linkedin.com/in "{position_query}" "{company_name}"'
|
||||||
for term in search_terms:
|
debug_print(f"Erstelle LinkedIn-Query: {query}")
|
||||||
try:
|
params = {
|
||||||
results = wikipedia.search(term, results=Config.WIKIPEDIA_SEARCH_RESULTS)
|
"engine": "google",
|
||||||
debug_print(f"Suchergebnisse für '{term}': {results}")
|
"q": query,
|
||||||
for title in results:
|
"api_key": serp_key,
|
||||||
try:
|
"hl": "de"
|
||||||
page = wikipedia.page(title, auto_suggest=False)
|
}
|
||||||
if self._validate_article(page, company_name, website):
|
try:
|
||||||
return page
|
response = requests.get("https://serpapi.com/search", params=params)
|
||||||
except (wikipedia.exceptions.DisambiguationError, wikipedia.exceptions.PageError) as e:
|
data = response.json()
|
||||||
debug_print(f"Seitenfehler: {str(e)}")
|
debug_print(f"SerpAPI-Response für Query '{query}': {data.get('organic_results', [])[:1]}")
|
||||||
continue
|
if "organic_results" in data and len(data["organic_results"]) > 0:
|
||||||
except Exception as e:
|
result = data["organic_results"][0]
|
||||||
debug_print(f"Suchfehler: {str(e)}")
|
title = result.get("title", "")
|
||||||
continue
|
debug_print(f"LinkedIn-Suchergebnis-Titel: {title}")
|
||||||
|
if "–" in title:
|
||||||
|
parts = title.split("–")
|
||||||
|
elif "-" in title:
|
||||||
|
parts = title.split("-")
|
||||||
|
else:
|
||||||
|
parts = [title]
|
||||||
|
if len(parts) >= 2:
|
||||||
|
name_part = parts[0].strip()
|
||||||
|
pos = parts[1].split("|")[0].strip()
|
||||||
|
name_parts = name_part.split(" ", 1)
|
||||||
|
if len(name_parts) == 2:
|
||||||
|
firstname, lastname = name_parts
|
||||||
|
else:
|
||||||
|
firstname = name_part
|
||||||
|
lastname = ""
|
||||||
|
debug_print(f"Kontakt gefunden: {firstname} {lastname}, Position: {pos}")
|
||||||
|
return {"Firmenname": company_name, "Website": website, "Vorname": firstname, "Nachname": lastname, "Position": pos}
|
||||||
|
else:
|
||||||
|
debug_print(f"Kontakt gefunden, aber unvollständige Informationen: {title}")
|
||||||
|
return {"Firmenname": company_name, "Website": website, "Vorname": "", "Nachname": "", "Position": title}
|
||||||
|
else:
|
||||||
|
debug_print(f"Keine LinkedIn-Ergebnisse für Query: {query}")
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
debug_print(f"Fehler bei der SerpAPI-Suche: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# ==================== GOOGLE SHEET HANDLER (Hauptdaten) ====================
|
def process_contacts():
|
||||||
|
debug_print("Starte LinkedIn-Kontaktsuche...")
|
||||||
|
gc = gspread.authorize(ServiceAccountCredentials.from_json_keyfile_name(
|
||||||
|
Config.CREDENTIALS_FILE, ["https://www.googleapis.com/auth/spreadsheets"]))
|
||||||
|
sh = gc.open_by_url(Config.SHEET_URL)
|
||||||
|
try:
|
||||||
|
contacts_sheet = sh.worksheet("Contacts")
|
||||||
|
except gspread.exceptions.WorksheetNotFound:
|
||||||
|
contacts_sheet = sh.add_worksheet(title="Contacts", rows="1000", cols="10")
|
||||||
|
header = ["Firmenname", "Website", "Vorname", "Nachname", "Position", "Anrede", "E-Mail"]
|
||||||
|
contacts_sheet.update("A1:G1", [header])
|
||||||
|
debug_print("Neues Blatt 'Contacts' erstellt und Header eingetragen.")
|
||||||
|
main_sheet = sh.sheet1
|
||||||
|
data = main_sheet.get_all_values()
|
||||||
|
positions = ["Serviceleiter", "IT-Leiter", "Leiter After Sales", "Leiter Einsatzplanung"]
|
||||||
|
new_rows = []
|
||||||
|
for idx, row in enumerate(data[1:], start=2):
|
||||||
|
company_name = row[1] if len(row) > 1 else ""
|
||||||
|
website = row[2] if len(row) > 2 else ""
|
||||||
|
debug_print(f"Verarbeite Firma: '{company_name}' (Zeile {idx}), Website: '{website}'")
|
||||||
|
if not company_name or not website:
|
||||||
|
debug_print("Überspringe, da Firmenname oder Website fehlt.")
|
||||||
|
continue
|
||||||
|
for pos in positions:
|
||||||
|
debug_print(f"Suche nach Position: '{pos}' bei '{company_name}'")
|
||||||
|
contact = search_linkedin_contact(company_name, website, pos)
|
||||||
|
if contact:
|
||||||
|
debug_print(f"Kontakt gefunden: {contact}")
|
||||||
|
new_rows.append([contact["Firmenname"], contact["Website"], contact["Vorname"], contact["Nachname"], contact["Position"], "", ""])
|
||||||
|
else:
|
||||||
|
debug_print(f"Kein Kontakt für Position '{pos}' bei '{company_name}' gefunden.")
|
||||||
|
if new_rows:
|
||||||
|
last_row = len(contacts_sheet.get_all_values()) + 1
|
||||||
|
range_str = f"A{last_row}:G{last_row + len(new_rows) - 1}"
|
||||||
|
contacts_sheet.update(range_str, new_rows)
|
||||||
|
debug_print(f"{len(new_rows)} Kontakte in 'Contacts' hinzugefügt.")
|
||||||
|
else:
|
||||||
|
debug_print("Keine Kontakte gefunden in der Haupttabelle.")
|
||||||
|
|
||||||
|
# ==================== NEUE FUNKTION: NUR WIKIPEDIA-SUCHE (MODUS 4) ====================
|
||||||
|
def process_wikipedia_only():
|
||||||
|
debug_print("Starte ausschließlich Wikipedia-Suche (Modus 4)...")
|
||||||
|
gc = gspread.authorize(ServiceAccountCredentials.from_json_keyfile_name(
|
||||||
|
Config.CREDENTIALS_FILE, ["https://www.googleapis.com/auth/spreadsheets"]))
|
||||||
|
sh = gc.open_by_url(Config.SHEET_URL)
|
||||||
|
main_sheet = sh.sheet1
|
||||||
|
data = main_sheet.get_all_values()
|
||||||
|
start_index = GoogleSheetHandler().get_start_index()
|
||||||
|
debug_print(f"Starte bei Zeile {start_index+1}")
|
||||||
|
for i, row in enumerate(data[1:], start=2):
|
||||||
|
if i < start_index:
|
||||||
|
continue
|
||||||
|
company_name = row[1] if len(row) > 1 else ""
|
||||||
|
website = row[2] if len(row) > 2 else ""
|
||||||
|
debug_print(f"Verarbeite Zeile {i}: {company_name}")
|
||||||
|
article = WikipediaScraper().search_company_article(company_name, website)
|
||||||
|
if article:
|
||||||
|
company_data = WikipediaScraper().extract_company_data(article.url)
|
||||||
|
else:
|
||||||
|
company_data = {
|
||||||
|
'url': 'k.A.',
|
||||||
|
'first_paragraph': 'k.A.',
|
||||||
|
'branche': 'k.A.',
|
||||||
|
'umsatz': 'k.A.',
|
||||||
|
'mitarbeiter': 'k.A.',
|
||||||
|
'categories': 'k.A.',
|
||||||
|
'full_infobox': 'k.A.'
|
||||||
|
}
|
||||||
|
wiki_values = [
|
||||||
|
row[10] if len(row) > 10 and row[10].strip() not in ["", "k.A."] else "k.A.",
|
||||||
|
company_data.get('url', 'k.A.'),
|
||||||
|
company_data.get('first_paragraph', 'k.A.'),
|
||||||
|
company_data.get('branche', 'k.A.'),
|
||||||
|
company_data.get('umsatz', 'k.A.'),
|
||||||
|
company_data.get('mitarbeiter', 'k.A.'),
|
||||||
|
company_data.get('categories', 'k.A.')
|
||||||
|
]
|
||||||
|
wiki_range = f"K{i}:Q{i}"
|
||||||
|
main_sheet.update(values=[wiki_values], range_name=wiki_range)
|
||||||
|
debug_print(f"Zeile {i} mit Wikipedia-Daten aktualisiert.")
|
||||||
|
current_dt = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
main_sheet.update(values=[[current_dt]], range_name=f"AH{i}")
|
||||||
|
main_sheet.update(values=[[Config.VERSION]], range_name=f"AI{i}")
|
||||||
|
time.sleep(Config.RETRY_DELAY)
|
||||||
|
debug_print("Wikipedia-Suche abgeschlossen.")
|
||||||
|
|
||||||
|
# ==================== GOOGLE SHEET HANDLER (für Hauptdaten) ====================
|
||||||
class GoogleSheetHandler:
|
class GoogleSheetHandler:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.sheet = None
|
self.sheet = None
|
||||||
@@ -374,57 +522,9 @@ def alignment_demo(sheet):
|
|||||||
sheet.update(values=[new_headers], range_name=header_range)
|
sheet.update(values=[new_headers], range_name=header_range)
|
||||||
print("Alignment-Demo abgeschlossen: Neue Spaltenüberschriften in Zeile 11200 geschrieben.")
|
print("Alignment-Demo abgeschlossen: Neue Spaltenüberschriften in Zeile 11200 geschrieben.")
|
||||||
|
|
||||||
# ==================== NEUER MODUS 4: NUR WIKIPEDIA-SUCHE ====================
|
|
||||||
def process_wikipedia_only():
|
|
||||||
debug_print("Starte ausschließlich Wikipedia-Suche (Modus 4)...")
|
|
||||||
gc = gspread.authorize(ServiceAccountCredentials.from_json_keyfile_name(
|
|
||||||
Config.CREDENTIALS_FILE, ["https://www.googleapis.com/auth/spreadsheets"]))
|
|
||||||
sh = gc.open_by_url(Config.SHEET_URL)
|
|
||||||
main_sheet = sh.sheet1
|
|
||||||
data = main_sheet.get_all_values()
|
|
||||||
# Wir gehen von der ersten Zeile ohne Timestamp in Spalte AH aus:
|
|
||||||
start_index = GoogleSheetHandler().get_start_index()
|
|
||||||
debug_print(f"Starte bei Zeile {start_index+1}")
|
|
||||||
for i, row in enumerate(data[1:], start=2):
|
|
||||||
if i < start_index:
|
|
||||||
continue
|
|
||||||
company_name = row[1] if len(row) > 1 else ""
|
|
||||||
website = row[2] if len(row) > 2 else ""
|
|
||||||
debug_print(f"Verarbeite Zeile {i}: {company_name}")
|
|
||||||
article = WikipediaScraper().search_company_article(company_name, website)
|
|
||||||
if article:
|
|
||||||
company_data = WikipediaScraper().extract_company_data(article.url)
|
|
||||||
else:
|
|
||||||
company_data = {
|
|
||||||
'url': 'k.A.',
|
|
||||||
'first_paragraph': 'k.A.',
|
|
||||||
'branche': 'k.A.',
|
|
||||||
'umsatz': 'k.A.',
|
|
||||||
'mitarbeiter': 'k.A.',
|
|
||||||
'categories': 'k.A.',
|
|
||||||
'full_infobox': 'k.A.'
|
|
||||||
}
|
|
||||||
wiki_values = [
|
|
||||||
row[10] if len(row) > 10 and row[10].strip() not in ["", "k.A."] else "k.A.",
|
|
||||||
company_data.get('url', 'k.A.'),
|
|
||||||
company_data.get('first_paragraph', 'k.A.'),
|
|
||||||
company_data.get('branche', 'k.A.'),
|
|
||||||
company_data.get('umsatz', 'k.A.'),
|
|
||||||
company_data.get('mitarbeiter', 'k.A.'),
|
|
||||||
company_data.get('categories', 'k.A.')
|
|
||||||
]
|
|
||||||
wiki_range = f"K{i}:Q{i}"
|
|
||||||
main_sheet.update(values=[wiki_values], range_name=wiki_range)
|
|
||||||
debug_print(f"Zeile {i} mit Wikipedia-Daten aktualisiert.")
|
|
||||||
current_dt = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
||||||
main_sheet.update(values=[[current_dt]], range_name=f"AH{i}")
|
|
||||||
main_sheet.update(values=[[Config.VERSION]], range_name=f"AI{i}")
|
|
||||||
time.sleep(Config.RETRY_DELAY)
|
|
||||||
debug_print("Wikipedia-Suche abgeschlossen.")
|
|
||||||
|
|
||||||
# ==================== MAIN PROGRAMM ====================
|
# ==================== MAIN PROGRAMM ====================
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print("Modi: 1 = regulärer Modus, 2 = Re-Evaluierungsmodus, 3 = Alignment-Demo, 4 = Nur Wikipedia-Suche")
|
print("Modi: 1 = regulärer Modus, 2 = Re-Evaluierungsmodus, 3 = Alignment-Demo, 4 = Nur Wikipedia-Suche, 5 = LinkedIn Contacts")
|
||||||
mode_input = input("Wählen Sie den Modus: ").strip()
|
mode_input = input("Wählen Sie den Modus: ").strip()
|
||||||
if mode_input == "2":
|
if mode_input == "2":
|
||||||
MODE = "2"
|
MODE = "2"
|
||||||
@@ -432,6 +532,8 @@ if __name__ == "__main__":
|
|||||||
MODE = "3"
|
MODE = "3"
|
||||||
elif mode_input == "4":
|
elif mode_input == "4":
|
||||||
MODE = "4"
|
MODE = "4"
|
||||||
|
elif mode_input == "5":
|
||||||
|
MODE = "5"
|
||||||
else:
|
else:
|
||||||
MODE = "1"
|
MODE = "1"
|
||||||
if MODE == "1":
|
if MODE == "1":
|
||||||
@@ -447,4 +549,6 @@ if __name__ == "__main__":
|
|||||||
processor.process_rows()
|
processor.process_rows()
|
||||||
elif MODE == "4":
|
elif MODE == "4":
|
||||||
process_wikipedia_only()
|
process_wikipedia_only()
|
||||||
|
elif MODE == "5":
|
||||||
|
process_contacts()
|
||||||
print(f"\n✅ Auswertung abgeschlossen ({Config.VERSION})")
|
print(f"\n✅ Auswertung abgeschlossen ({Config.VERSION})")
|
||||||
|
|||||||
Reference in New Issue
Block a user